// cookie 存储形式：MoreTVWeChatUIDS=muid123456qwerty,muid234567wertyu;muid123456qwerty=192.168.1.101,8089,wxsessionid_13786765342,小米盒子1;muid234567wertyu=192.168.1.102,8089,wxsessionid_13786776866,乐视盒子

// "http://172.249.0.149,12580,mygicaTVbox,wxsessionid_1383622364383,http://172.249.0.149:12580"
//["http://172.249.0.172", "12580", "mygicaTVbox", "wxsessionid_1400231501698", "http://172.249.0.172:12580"]
var UIDKey = 'MoreTVWeChatUIDS';
var uidPref = 'muid';
var searchStoreKey = 'searchKey';
var searchTotalKey = 'searchTotalKey';
var heartbeatUrl = '';
var timeStampKey = 'timeStampKey';
var showHideFlagKey = 'showHideFlagKey';
var subScriptionKey = 'subScriptionKey';
var subScriptionSeparate = '-';
var subScriptionPrefix = 'subscription-';
var subScriptionGroupType = ['tag_top','tag_movie','tag_tv','tag_sports','tag_zongyi','tag_comic','tag_kids','tag_jilu','tag_mv','tag_hot'];//订阅分组code，与rss_site.json中的code保持一致
var mySubScriptionLongRowHeight;
var mySubScriptionShortRowHeight;
var mySubScriptionHeaderRowHeight;
var accessInfoLocalKey = 'accessInfo';
var request_access_token = '';
var currentWXUser = null;
var WXUserInfoLocalKey = 'wxUserInfo';
var GET_ACCESS_TOKEN_URL = 'http://bus.moretv.com.cn/bus/get_access_token?callback=?';
var GET_WX_USER_INFO_URL = 'http://bus.moretv.com.cn/client/weixin/userinfo/';
var commentsScroll;
var programsScroll;
var IScrollMsg = {
    Up:{More:'往上拉加载更多...',Release:'释放继续加载...',Loading:'正在加载...'},
    Down:{More:'往下拉刷新...',Release:'释放刷新...',Loading:'正在刷新...'}
};
function setCookie(name,value,expire){
    var expireDate = new Date ();
    if(typeof expire != 'undefined' && expire != null){
        expireDate.setTime(expireDate.getTime() + expire);
    }
    if(browser.versions.ios){
        localStorage[name] = value;
    }else{
        document.cookie = name + "=" + escape(value) + ((typeof expire == 'undefined' || expire == null) ? "" : "; expires=" + expireDate.toGMTString())+";path=/";
    }
}

function setSimKeyCookie(name,value){
    var Days = 30;
    var exp = new Date();
    exp.setTime(exp.getTime() + Days*24*60*60*1000);
    if(browser.versions.ios){
        localStorage[name] = value;
    }else{
        document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
    }
}

function getCookie(name) {
    if (browser.versions.ios) {
        return localStorage[name];
    } else {
        if (document.cookie.length > 0) {
            var begin = document.cookie.indexOf(name + "=");
            if (begin != -1) {
                begin += name.length + 1;//cookie值的初始位置
                var end = document.cookie.indexOf(";", begin);//结束位置
                if (end == -1) {
                    end = document.cookie.length;
                }//没有;则end为字符串结束位置
                return unescape(document.cookie.substring(begin, end));
            }
        }
        return null;
    }
}
function getSimKeyCookie(name) {
    if (browser.versions.ios) {
        return localStorage[name];
    } else {
        var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
        if(arr=document.cookie.match(reg))
            return unescape(arr[2]);
        else
            return null;
    }
}
function delCookie(name) {
    // 该函数检查下cookie是否设置，如果设置了则将过期时间调到过去的时间;
    //剩下就交给操作系统适当时间清理cookie啦
    if (browser.versions.ios){
        localStorage.removeItem(name);
    } else {
        if (getCookie(name)) {
            document.cookie = name + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
        }
    }
}
function deleteDevice(uid){
    delCookie(uidPref+uid);
    var uids = getCookie(UIDKey);
    if(uids){
        if(uids.indexOf(',') != -1){
            var uidstr = '';
            var uidArr = uids.split(',');
            var tempArr = [];
            for (var i = 0; i < uidArr.length; i++) {
                if (uid != uidArr[i]) {
                    tempArr.push(uidArr[i]);
                }
            }
            if (tempArr.length > 0) {
                uidstr = tempArr.join(',');
            }
            setCookie(UIDKey, uidstr);
        }else{
            if(uids == uid){
                setCookie(UIDKey, '');
            }
        }
    }
}
function storeUID(info_param,lastest){
    var uid = info_param.userid;
    var uids = '';
    if (browser.versions.ios){
        uids = localStorage[UIDKey];
    }else{
        var cookies = document.cookie;
        if(cookies.length >0){
            uids = getCookie(UIDKey);
        }
    }
    if(uids){
        if(uids.indexOf(uid) != -1){
            var uidArr = uids.split(',');
            if (uidArr[0] == uid) {

            } else {
                var tempArr = [];
                for (var i = 0; i < uidArr.length; i++) {
                    if (uidArr[i] != uid) {
                        tempArr.push(uidArr[i]);
                    }
                }
                if (lastest) {
                    tempArr.push(uid);
                } else {
                    tempArr.unshift(uid);
                }
                uids = tempArr.join(',');
            }
        }else{
            var uidArr = uids.split(',');
            var tempArr = [];
            if(uidArr.length>=5){
                for(var i=uidArr.length-1; i>=uidArr.length-4;i--){
                    tempArr.push(uidArr[i]);
                }
            }else{
                tempArr = uidArr;
            }
            var _temp = [];
            for(var j=0; j<tempArr.length;j++){
                var infos = getCookie(uidPref+tempArr[j]);
                if(infos){
                    var infosArr = infos.split(',');
                    if (infosArr.length > 0) {
                        if (info_param.name == infosArr[2] && info_param.ip == infosArr[0]) {
                            delCookie(uidPref + tempArr[j]);
                        } else {
                            _temp.push(tempArr[j]);
                        }
                    }
                }
            }
            tempArr = _temp;
            if(lastest){
                tempArr.push(uid);
            }else{
                tempArr.unshift(uid);
            }
            uids = tempArr.join(',');
        }
    }else{
        uids = uid;
    }
    setCookie(UIDKey,uids);
}
function storeValue(uid,value){
    setCookie(uidPref+uid,value);
}
function deleteAllCookie(){
    var uids = getCookie(UIDKey);
    if(uids){
        if(uids.indexOf(',')){
            var uidArr = uids.split(',');
            for(var  i=0; i<uidArr.length; i++){
                deleteDevice(uidArr[i]);
            }
        }else{
            deleteDevice(uids);
        }
    }
}
//////////////计算列表图片尺寸
function autoImgHeight(contentType){
    var shortInfo = $('.list .shortInfo').length;
    if(shortInfo > 0){
        var img_width = $(".list li:first-child").find("img").width();
        var img_height = Math.floor(120*img_width/180);
        $(".list li").find("img").attr("height",img_height);
    }else{
        var img_width = $(".list li:first-child").find("img").width();
        var img_height = Math.floor(202*img_width/134);
        $(".list li").find("img").attr("height",img_height);
    }

};
var resizeTimer = null;
$(window).resize(function(){
	resizeTimer = resizeTimer ? null : setTimeout(autoImgHeight,0);
});
function getDefaultImgSrc(contentType){
	autoImgHeight(contentType);
    var defaultSrc = '';
    switch (contentType){
        case WeChatHelperConstants.ContentType.MOVIE:
            defaultSrc = 'images/default.png';
            break;
        case WeChatHelperConstants.ContentType.TV:
            defaultSrc = 'images/default.png';
            break;
        case WeChatHelperConstants.ContentType.ZONGYI:
            defaultSrc = 'images/default.png';
            break;
        case WeChatHelperConstants.ContentType.KIDS:
            defaultSrc = 'images/default.png';
            break;
        case WeChatHelperConstants.ContentType.COMIC:
            defaultSrc = 'images/default.png';
            break;
        case WeChatHelperConstants.ContentType.SHORTVIDEO:
            defaultSrc = 'images/default2.png';
            break;
        case WeChatHelperConstants.ContentType.MV:
            defaultSrc = 'images/default2.png';
            break;
        case WeChatHelperConstants.ContentType.JILU:
            defaultSrc = 'images/default.png';
            break;
        case WeChatHelperConstants.ContentType.XIQU:
            defaultSrc = 'images/default2.png';
            break;
        case WeChatHelperConstants.ContentType.SPORTS:
            defaultSrc = 'images/default2.png';
            break;
        case WeChatHelperConstants.ContentType.ALL:
            defaultSrc = 'images/default.png';
            break;
        case WeChatHelperConstants.ContentType.CAST:
            defaultSrc = 'images/default.png';
            break;
        case WeChatHelperConstants.DefaultImgBgType.ChannelIcon:
            defaultSrc = 'images/channel_default.png';
            break;
        case WeChatHelperConstants.DefaultImgBgType.Person:
            defaultSrc = 'images/default.png';
            break;
        case WeChatHelperConstants.DefaultImgBgType.SubScriptionIcon:
            defaultSrc = 'images/subscription_default.png';
    }
    return defaultSrc;
}
function makeInfoPage(sid) {
    /*
    _cache.getItem('detail_cache_'+sid,function(e){
        alert('from cache');
        infoAss(JSON.parse(e));
        return;
    },function(){
        alert('no cache');
        var Para = {
            sid:sid
        };
        commonAjax(SID_URL, Para,
            function (res) {
                if (WeChatHelperConstants.CommonAjaxTimeStamp == Number(this)) {
                    _cache.setItem('detail_cache_'+sid,JSON.stringify(res));
                    infoAss(res);
                }
            }
        );
    });
    */
    var Para = {
        sid:sid
    };
    commonAjax(SID_URL, Para,
        function (res) {
            if (WeChatHelperConstants.CommonAjaxTimeStamp == Number(this)) {
                infoAss(res);
            }
        }
    );
};
function infoAss(res){
    WeChatHelperConstants.AnthologyCurrentPageIndex = 1;
    res = res.program;
    WeChatHelperConstants.CurrentInfoRes = res;
    var metadata = res.metadata;
    var contentType = metadata.contentType;
    $('#title').html(metadata.title);
    var score = getScore(res);
    $('#score').html(score);
    var stars = getStar(score);
    if(stars.length==5){
        $('#score_star').css('width',stars[3]+''+stars[4]+'%');
    }
//                $('#program_title').html(metadata.title);
    $('#program_pic').html('<img class="serimg" src="'+getDefaultImgSrc(contentType)+'" url="'+metadata.icon1+'" />');
    $('#program_details').html(getProgramDetailInfo(res));
    $('#program_intro').html(metadata.intro);
    makeSelectAnthologyTermPageValueArr(res);
    var episodesHtmlStr = getEpisodesHtml(1);
    if(episodesHtmlStr){
        $('#program_episodes').html(episodesHtmlStr);
    }
    if($('#info_play_btn').length > 0){
        $('#info_play_btn').attr('href','javascript:gotoPlay(\''+metadata.sid+'\','+'\''+metadata.sid+'\',\''+metadata.contentType+'\','+WeChatHelperConstants.PlayType.LargeProgram+')');
    }
    if($('#info_play_btn2').length > 0){
        $('#info_play_btn2').attr('href','javascript:gotoPlay(\''+metadata.sid+'\','+'\''+metadata.sid+'\',\''+metadata.contentType+'\','+WeChatHelperConstants.PlayType.Local+')');
    }
    var imgArr = $('#program_pic').find('.serimg');
    loadImg(imgArr,getDefaultImgSrc(contentType));
    $(".episodes li:first-child").attr("class","visited");
    $(".episodes li").click(function(){
        $(this).addClass("visited");
        $(this).siblings().removeClass("visited");
    });
    $('#loading2').css('display','none');
}
function getProgramDetailInfo(res){
    var metadata = res.metadata;
    var htmlStr = '';
    var contentType = metadata.contentType;
    var year = metadata.year || '未知';
    var area = metadata.area || '未知';
    var intro = metadata.intro;
    var duration = metadata.duration || '未知';
    try{
        var minutes = parseInt(duration,10);
        if(!isNaN(minutes) && minutes != 0){
            duration = secondToTimeFormat(minutes * 60);
            var durationArr = duration.split(':');
            duration = durationArr[0] + '小时' + durationArr[1] + '分钟';
        }else{
            duration = '未知';
        }
    }catch(e){
        duration = '未知';
    };
    var type = '';
    if (metadata.tag && metadata.tag.length > 0) {
        for (var k in metadata.tag) {
            if (k > 1)break;
            type += metadata.tag[k] + '/';
        }
        type = type.slice(0, -1);
    } else {
        type = '未知';
    }
    var isHd = metadata.isHd ? (''+metadata.isHd) : '0';
    var toastmaster = (metadata.toastmaster && metadata.toastmaster.length>0) ?metadata.toastmaster.join('/') :'未知';
    var director = (metadata.director && metadata.director.length>0) ?metadata.director.join('/') :'未知';
    var cast = (metadata.cast && metadata.cast.length>0) ?metadata.cast.join('/') :'未知';
    var sourceFrom = metadata.station ?  metadata.station : '未知';
    switch(contentType){
        case WeChatHelperConstants.ContentType.MOVIE:
            htmlStr = '<p class="textShadow2"><strong>导演:</strong> '+director+'</p>' +
                '<p class="textShadow2"><strong>主演:</strong> '+cast+'</p>' +
                '<p class="textShadow2"><strong>类型:</strong> '+type+'</p>' +
                '<p class="textShadow2"><strong>地区:</strong> '+area+'</p>' +
                '<p class="textShadow2"><strong>年代:</strong> '+year+'</p>' +
                '<p class="textShadow2"><strong>片长:</strong> '+duration+'</p>';
            break;
        case WeChatHelperConstants.ContentType.ZONGYI:
            var str = getDetailEpisodeInfoStr(res);
            htmlStr = '<p class="textShadow2">' +str+'</p>' +
                '<p class="textShadow2"><strong>主持人:</strong> '+toastmaster+'</p>' +
                '<p class="textShadow2"><strong>来自:</strong> '+sourceFrom+'</p>' +
                '<p class="textShadow2"><strong>类型:</strong> '+type+'</p>' +
                '<p class="textShadow2"><strong>地区:</strong> '+area+'</p>';
            break;
        case WeChatHelperConstants.ContentType.JILU:
            var str = getDetailEpisodeInfoStr(res);
            htmlStr = '<p class="textShadow2">' +str+'</p>' +
                '<p class="textShadow2"><strong>主持人:</strong> '+toastmaster+'</p>' +
                '<p class="textShadow2"><strong>来自:</strong> '+sourceFrom+'</p>' +
                '<p class="textShadow2"><strong>类型:</strong> '+type+'</p>' +
                '<p class="textShadow2"><strong>地区:</strong> '+area+'</p>';
            break;
        default:
            var str = getDetailEpisodeInfoStr(res);
            htmlStr = '<p class="textShadow2"><strong>导演:</strong> '+director+'</p>' +
                '<p class="textShadow2"><strong>主演:</strong> '+cast+'</p>' +
                '<p class="textShadow2"><strong>类型:</strong> '+type+'</p>' +
                '<p class="textShadow2"><strong>地区:</strong> '+area+'</p>' +
                '<p class="textShadow2"><strong>年代:</strong> '+year+'</p>' +
                '<p class="textShadow2">' +str+'</p>';
            break;
    }
    return htmlStr;
};
function getStar(score){
    var star = [];
    score += '';
    if(score.indexOf('.')==-1){
        score += '.0';
    }
    if(score == '.0'){
        score = '0.0';
    }
    var sArr = score.split('.');
    var oPart = parseInt(sArr[0],10);
    var tPart = parseInt(sArr[1],10);
    star[0] = parseInt(oPart/2,10);// 全亮的星星
    if(oPart % 2 == 0){
        star[0] = oPart/2;
        star[1] = tPart == 0 ? 0 : 1 ;// 半亮的星星
    }else{
        star[0] = parseInt(oPart/2,10);
        star[1] = 1;// 半亮的星星
    }
    star[2] = 5-star[0]-star[1];// 全灰的星星
    star[3] = oPart;
    star[4] = tPart;
    return star;
};
function getScore(res){
    var score = '6.0';
    if(typeof res.score !== 'undefined' && typeof res.score.score !== 'undefined'){
        if(res.score.score != '' && res.score.score != '0.0' && res.score.score != '0'){
            score = res.score.score
        }else{
            if(typeof res.metadata.score !== 'undefined' && res.metadata.score != '' && res.metadata.score != '0.0' && res.metadata.score != '0'){
                score = res.metadata.score;
            }
        }
    }
    return score;
};
function getDetailEpisodeInfoStr(res){
    var str = '';
    var contentType = res.metadata.contentType;
    if (contentType == WeChatHelperConstants.ContentType.ZONGYI || contentType == WeChatHelperConstants.ContentType.JILU) {
        try {
            if (res.metadata.isTimeItem == '1') {
                str += '<span class="episodeText orange">更新至' + res.monthGroup[0][0].metadata.episode + '期</span>';
            } else {
                try {
                    var updating = isProgramUpdating(res);
                    if (updating) {
                        str = '<span class="episodeText orange">更新至' + res.episodes[0].metadata.episode + '期</span>';
                    } else {
                        str = '<span class="orange">' + res.metadata.episodeCount+'期全</span>';
                    }
                } catch (e) {
                }
                ;
            }
        } catch (e) {
        };
    }
    if (contentType == WeChatHelperConstants.ContentType.TV || contentType == WeChatHelperConstants.ContentType.COMIC || contentType == WeChatHelperConstants.ContentType.KIDS) {
        try {
            var updating = isProgramUpdating(res);
            if (updating) {
                str = '<span class="episodeText orange">更新至' + res.episodes[0].metadata.episode + '集</span>';
            } else {
                str = '<span class="orange">' + res.metadata.episodeCount+'集全</span>';
            }
        } catch (e) {
        };
    }
    return str;
}
function getSearchEpisodeInfoStr(contentType,episode,episodeCount,score,duration){
    var str = '';
    if(contentType == WeChatHelperConstants.ContentType.MOVIE){
        if(typeof score != 'undefined' && score != '0.0' && score != '0'){
            score = score.replace(/\.(\d)+/g,'<em class="smallRed">$&</em>')
            str = '<em class="bigRed">'+score+'</em>';
        }else{
            str = '<em class="bigRed">6<em class="smallRed">.0</em></em>';
        }
    }
    if (contentType == WeChatHelperConstants.ContentType.ZONGYI || contentType == WeChatHelperConstants.ContentType.JILU) {
        try {
            if(episode.length == 8){
                episode = episode.slice(4);
                str = '<span class="episodeText">更新至' + episode + '期</span>';
            }else{
                try{
                    episode = parseInt(episode,10);
                    episodeCount = parseInt(episodeCount,10);
                }catch(e){}
                if(episode < episodeCount){
                    str = '<span class="episodeText">更新至' + episode + '期</span>';
                }else{
                    str = episodeCount + '期全';
                }
            }
        } catch (e) {
        };
    }
    if (contentType == WeChatHelperConstants.ContentType.TV || contentType == WeChatHelperConstants.ContentType.COMIC || contentType == WeChatHelperConstants.ContentType.KIDS) {
        try {
            try{
                episode = parseInt(episode,10);
                episodeCount = parseInt(episodeCount,10);
            }catch(e){}
            if(episode < episodeCount){
                str = '<span class="episodeText">更新至' + episode + '集</span>';
            }else{
                str = episodeCount + '集全';
            }
        } catch (e) {
        };
    }
    if (contentType == WeChatHelperConstants.ContentType.SHORTVIDEO) {
        try {
            if(duration){
                str = '<span class="episodeText">'+duration+'</span>';
            }else{
                str = '00:00';
            }
        } catch (e) {
        };
    }
    return str;
}
function getEpisodesHtml(page,currentEpisode){
    var res = WeChatHelperConstants.CurrentInfoRes;
    var metadata = res.metadata;
    var contentType = metadata.contentType;
    var htmlStr = '';
    var count = 0;
    switch(contentType){
        case WeChatHelperConstants.ContentType.MOVIE:
            break;
        case WeChatHelperConstants.ContentType.ZONGYI:
            if(metadata.isTimeItem == '1'){
                if (WeChatHelperConstants.SelectAnthologyTermPageValueArr[page]) {
                    $('#program_episodes').attr('class','onlyOne');
                    for (var i = 0; i < WeChatHelperConstants.SelectAnthologyTermPageValueArr[page].length; i++) {
                        count ++;
                        if(currentEpisode && WeChatHelperConstants.SelectAnthologyTermPageValueArr[page][i].Value.metadata.sid == currentEpisode){
                            WeChatHelperConstants.FindCurrentEpisode = true;
                            WeChatHelperConstants.AnthologyCurrentPageIndex = page;
                            WeChatHelperConstants.AnthologyScrollLine = (page-1)*40+count;
                            htmlStr += '<li class="visited" id="goto_position"><a href="javascript:gotoPlay(\''+metadata.sid+'\''+','+'\''+WeChatHelperConstants.SelectAnthologyTermPageValueArr[page][i].Sid+'\',\''+metadata.contentType+'\','+WeChatHelperConstants.PlayType.LargeProgram+');">'+WeChatHelperConstants.SelectAnthologyTermPageValueArr[page][i].Value.metadata.episode + '&nbsp;&nbsp;' + WeChatHelperConstants.SelectAnthologyTermPageValueArr[page][i].Value.metadata.title+'</a></li>';
                        } else{
                            htmlStr += '<li><a href="javascript:gotoPlay(\''+metadata.sid+'\''+','+'\''+WeChatHelperConstants.SelectAnthologyTermPageValueArr[page][i].Sid+'\',\''+metadata.contentType+'\','+WeChatHelperConstants.PlayType.LargeProgram+');">'+WeChatHelperConstants.SelectAnthologyTermPageValueArr[page][i].Value.metadata.episode + '&nbsp;&nbsp;' + WeChatHelperConstants.SelectAnthologyTermPageValueArr[page][i].Value.metadata.title+'</a></li>';
                        }
                    }
                }
            }else{
                if (WeChatHelperConstants.SelectAnthologyTermPageValueArr[page]) {
                    $('#program_episodes').attr('class','');
                    for (var i = 0; i < WeChatHelperConstants.SelectAnthologyTermPageValueArr[page].length; i++) {
                        count++;
                        if(currentEpisode && WeChatHelperConstants.SelectAnthologyTermPageValueArr[page][i].Value.metadata.sid == currentEpisode){
                            WeChatHelperConstants.FindCurrentEpisode = true;
                            WeChatHelperConstants.AnthologyCurrentPageIndex = page;
                            WeChatHelperConstants.AnthologyScrollLine = (page-1)*80+count;
                            htmlStr += '<li class="visited" id="goto_position"><a href="javascript:gotoPlay(\''+metadata.sid+'\''+','+'\''+WeChatHelperConstants.SelectAnthologyTermPageValueArr[page][i].Sid+'\',\''+metadata.contentType+'\','+WeChatHelperConstants.PlayType.LargeProgram+');">'+WeChatHelperConstants.SelectAnthologyTermPageValueArr[page][i].Value.metadata.episode + '&nbsp;&nbsp;' + WeChatHelperConstants.SelectAnthologyTermPageValueArr[page][i].Value.metadata.title+'</a></li>';
                        } else{
                            htmlStr += '<li><a href="javascript:gotoPlay(\''+metadata.sid+'\''+','+'\''+WeChatHelperConstants.SelectAnthologyTermPageValueArr[page][i].Sid+'\',\''+metadata.contentType+'\','+WeChatHelperConstants.PlayType.LargeProgram+');">'+WeChatHelperConstants.SelectAnthologyTermPageValueArr[page][i].Value.metadata.episode + '&nbsp;&nbsp;' + WeChatHelperConstants.SelectAnthologyTermPageValueArr[page][i].Value.metadata.title+'</a></li>';
                        }
                    }
                }
            }
            break;
        case WeChatHelperConstants.ContentType.JILU:
            if (WeChatHelperConstants.SelectAnthologyTermPageValueArr[page]) {
                $('#program_episodes').attr('class','onlyOne');
                for (var i = 0; i < WeChatHelperConstants.SelectAnthologyTermPageValueArr[page].length; i++) {
                    count ++;
                    if(currentEpisode && WeChatHelperConstants.SelectAnthologyTermPageValueArr[page][i].Value.metadata.sid == currentEpisode){
                        WeChatHelperConstants.FindCurrentEpisode = true;
                        WeChatHelperConstants.AnthologyCurrentPageIndex = page;
                        WeChatHelperConstants.AnthologyScrollLine = (page-1)*40+count;
                        htmlStr += '<li class="visited" id="goto_position"><a href="javascript:gotoPlay(\''+metadata.sid+'\''+','+'\''+WeChatHelperConstants.SelectAnthologyTermPageValueArr[page][i].Sid+'\',\''+metadata.contentType+'\','+WeChatHelperConstants.PlayType.LargeProgram+');">'+WeChatHelperConstants.SelectAnthologyTermPageValueArr[page][i].Value.metadata.episode + '&nbsp;&nbsp;' + WeChatHelperConstants.SelectAnthologyTermPageValueArr[page][i].Value.metadata.title+'</a></li>';
                    } else{
                        htmlStr += '<li><a href="javascript:gotoPlay(\''+metadata.sid+'\''+','+'\''+WeChatHelperConstants.SelectAnthologyTermPageValueArr[page][i].Sid+'\',\''+metadata.contentType+'\','+WeChatHelperConstants.PlayType.LargeProgram+');">'+WeChatHelperConstants.SelectAnthologyTermPageValueArr[page][i].Value.metadata.episode + '&nbsp;&nbsp;' + WeChatHelperConstants.SelectAnthologyTermPageValueArr[page][i].Value.metadata.title+'</a></li>';
                    }
                }
            }
            break;
        default:
            if (WeChatHelperConstants.SelectAnthologyTermPageValueArr[page]) {
                $('#program_episodes').attr('class','');
                for (var i = 0; i < WeChatHelperConstants.SelectAnthologyTermPageValueArr[page].length; i++) {
                    count++;
                    if(currentEpisode && WeChatHelperConstants.SelectAnthologyTermPageValueArr[page][i].Value.metadata.sid == currentEpisode){
                        WeChatHelperConstants.FindCurrentEpisode = true;
                        WeChatHelperConstants.AnthologyCurrentPageIndex = page;
                        WeChatHelperConstants.AnthologyScrollLine = (page-1)*80+count;
                        htmlStr += '<li class="visited" id="goto_position"><a href="javascript:gotoPlay(\''+metadata.sid+'\''+','+'\''+WeChatHelperConstants.SelectAnthologyTermPageValueArr[page][i].Sid+'\',\''+metadata.contentType+'\','+WeChatHelperConstants.PlayType.LargeProgram+');">'+WeChatHelperConstants.SelectAnthologyTermPageValueArr[page][i].Value.metadata.episode+'</a></li>';
                    } else{
                        htmlStr += '<li><a href="javascript:gotoPlay(\''+metadata.sid+'\''+','+'\''+WeChatHelperConstants.SelectAnthologyTermPageValueArr[page][i].Sid+'\',\''+metadata.contentType+'\','+WeChatHelperConstants.PlayType.LargeProgram+');">'+WeChatHelperConstants.SelectAnthologyTermPageValueArr[page][i].Value.metadata.episode+'</a></li>';
                    }
                }
            }
            break;
    }
    return htmlStr;
};
function makeSelectAnthologyTermPageValueArr(res) {
    WeChatHelperConstants.SelectAnthologyTermPageValueArr = [
        []
    ];
    if (contentType == WeChatHelperConstants.ContentType.MOVIE) {
        return;
    }
    var contentType = res.metadata.contentType;
    var isTimeItem = ('' + res.metadata.isTimeItem);
    var pageArr = [];
    if (contentType == WeChatHelperConstants.ContentType.ZONGYI || contentType == WeChatHelperConstants.ContentType.JILU) {
        if (isTimeItem == '1') {
            for (var i = 0; i < res.monthGroup.length; i++) {
                for (var j = 0; j < res.monthGroup[i].length; j++) {
                    pageArr.push({'Value':res.monthGroup[i][j], 'Sid':res.monthGroup[i][j].metadata.sid});
                    if (pageArr.length == 40) {
                        WeChatHelperConstants.SelectAnthologyTermPageValueArr.push(pageArr);
                        pageArr = [];
                    }
                }
            }
            if (pageArr.length < 40 && pageArr.length > 0) {
                WeChatHelperConstants.SelectAnthologyTermPageValueArr.push(pageArr);
            }
        } else {
            for (var k = 0; k < res.episodes.length; k++) {
                pageArr.push({ 'Value':res.episodes[k], 'Sid':res.episodes[k].metadata.sid});
                if (pageArr.length == 80) {
                    WeChatHelperConstants.SelectAnthologyTermPageValueArr.push(pageArr);
                    pageArr = [];
                }
            }
            if (pageArr.length < 80 && pageArr.length > 0) {
                WeChatHelperConstants.SelectAnthologyTermPageValueArr.push(pageArr);
            }
        }
    } else {
        for (var k = 0; k < res.episodes.length; k++) {
            pageArr.push({ 'Value':res.episodes[k], 'Sid':res.episodes[k].metadata.sid});
            if (pageArr.length == 80) {
                WeChatHelperConstants.SelectAnthologyTermPageValueArr.push(pageArr);
                pageArr = [];
            }
        }
        if (pageArr.length < 80 && pageArr.length > 0) {
            WeChatHelperConstants.SelectAnthologyTermPageValueArr.push(pageArr);
        }
    }

};
function isProgramUpdating(res){
    var episodeCount = 0;
    var episodeLength = 0;
    if(res) {
        try{
            // 总集数
            episodeCount = parseInt(res.metadata.episodeCount,10)?parseInt(res.metadata.episodeCount,10):0;
            // 目前更新到的集数
            episodeLength = res.episodes.length;
            return episodeLength < episodeCount;
        }catch(e){
            return false;
        };
    }
    return false;
};
function gotoPlay(pSid,sSid,contentType,playType,title){
    if(typeof playType != 'undefined' && null != playType){
        playType = parseInt(playType,10);
    }
    // 手机选集播放
    if($('#push_1').attr('class') == 'visited'){
        playType = WeChatHelperConstants.PlayType.Local;
    }
    if(!sSid){
        sSid = pSid;
    }
    WeChatHelperConstants.DetailpSid = pSid;
    WeChatHelperConstants.DetailsSid = sSid;
    WeChatHelperConstants.DetailContentType = contentType;
    WeChatHelperConstants.DetailPlayType = playType;
    switch(playType){
        case  WeChatHelperConstants.PlayType.Live:
            var page_path = sessionStorage.getItem('pagePath');
            if(page_path){
                upLog(WeChatHelperConstants.LogType.Play,WeChatHelperConstants.LogPlayType.LivePlay+'_'+page_path+'_'+pSid+'_'+sSid);
            }else{
                upLog(WeChatHelperConstants.LogType.Play,WeChatHelperConstants.LogPlayType.LivePlay+'_'+WeChatHelperConstants.DetailPageFrom.WeiXinSearch+'_'+pSid+'_'+sSid);//微信客户端搜索直播频道直接跳转进入播放
            }
            break;
        case WeChatHelperConstants.PlayType.Local:
            upLog(WeChatHelperConstants.LogType.Play,WeChatHelperConstants.LogPlayType.LocalPlay+'_'+sessionStorage.getItem('pageFrom')+'_'+pSid+'_'+sSid);
            var h = getScrollHeight();
            var top = getScrollTop() + 120;
            $('#loading2').css({'height':h+'px','display':'block'});
            $('#loading2 .loadingImg').css('top',top+'px');
            $('#loading2 .loadingtext').css('top',(top+10)+'px');
            try {
                WeChatHelperConstants.WeiXinJSBridge.invoke('getNetworkType', {},
                    function (e) {
                        if (e.err_msg != 'network_type:wifi') {
                            $('#loading2').css('display', 'none');
                            popNwtWorkAlert();
                            return;
                        } else {
                            clearTimeout(WeChatHelperConstants.CommonAjaxTimer);
                            var timeout = true;
                            WeChatHelperConstants.CommonAjaxTimer = setTimeout(function () {
                                if (timeout) {
                                    // 验证超时，弹出输入PING
                                    $('#loading2').css('display', 'none');
                                    $('#conflict').css('display', 'none');
                                    $('#tip_text').html('连接超时，请检查网络');
                                    $('#conflict').fadeIn(300, function () {
                                        setTimeout(function () {
                                            $('#conflict').fadeOut(1000);
                                        }, 2000);
                                    });
                                    return;
                                }
                            }, WeChatHelperConstants.CommonAjaxTimeout);
                            commonAjax(SID_URL, {sid: sSid},
                                function (res) {
                                    timeout = false;
                                    if (!timeout) {
                                        $('#loading2').css('display', 'none');
                                        var status = -1;
                                        try {
                                            status = parseInt(res.status, 10);
                                        } catch (e) {
                                        }
                                        ;
                                        // 节目正常
                                        if (status >= 0) {
                                            if (res.program.mediaFiles && res.program.mediaFiles.length > 0) {
                                                var url = res.program.mediaFiles[0].url.replace('&flag=.moretv', '');
                                                var pcsReg = /^http:\/\/pcs\S*\.baidu\S*/;
                                                var yunpanReg = /^http:\/\/\S*yunpan\.\S*/;
                                                if(pcsReg.test(url) || yunpanReg.test(url)){
                                                    $('#conflict').css('display', 'none');
                                                    $('#tip_text').html('云盘资源无法直接播放');
                                                    $('#conflict').fadeIn(300, function () {
                                                        setTimeout(function () {
                                                            $('#conflict').fadeOut(1000);
                                                        }, 2000);
                                                    });
                                                } else{
                                                    window.top.location.href = url;
                                                }
                                            } else {
                                                $('#conflict').css('display', 'none');
                                                $('#tip_text').html('该节目已失效');
                                                $('#conflict').fadeIn(300, function () {
                                                    setTimeout(function () {
                                                        $('#conflict').fadeOut(1000);
                                                    }, 2000);
                                                });
                                            }
                                        } else {
                                            // 节目下线提示信息
                                            $('#conflict').css('display', 'none');
                                            $('#tip_text').html('该节目已下线');
                                            $('#conflict').fadeIn(300, function () {
                                                setTimeout(function () {
                                                    $('#conflict').fadeOut(1000);
                                                }, 2000);
                                            });
                                        }
                                        return;
                                    }
                                }
                            );
                        }
                    });
            } catch (e) {
                clearTimeout(WeChatHelperConstants.CommonAjaxTimer);
                var timeout = true;
                WeChatHelperConstants.CommonAjaxTimer = setTimeout(function () {
                    if (timeout) {
                        // 验证超时，弹出输入PING
                        $('#loading2').css('display', 'none');
                        $('#conflict').css('display', 'none');
                        $('#tip_text').html('连接超时，请检查网络');
                        $('#conflict').fadeIn(300, function () {
                            setTimeout(function () {
                                $('#conflict').fadeOut(1000);
                            }, 2000);
                        });
                        return;
                    }
                }, WeChatHelperConstants.CommonAjaxTimeout);
                commonAjax(SID_URL, {sid: sSid},
                    function (res) {
                        timeout = false;
                        if (!timeout) {
                            $('#loading2').css('display', 'none');
                            var status = -1;
                            try {
                                status = parseInt(res.status, 10);
                            } catch (e) {
                            }
                            ;
                            // 节目正常
                            if (status >= 0) {
                                if (res.program.mediaFiles && res.program.mediaFiles.length > 0) {
                                    var url = res.program.mediaFiles[0].url.replace('&flag=.moretv', '');
                                    var pcsReg = /^http:\/\/pcs\S*\.baidu\S*/;
                                    var yunpanReg = /^http:\/\/\S*yunpan\.\S*/;
                                    if(pcsReg.test(url) || yunpanReg.test(url)){
                                        $('#conflict').css('display', 'none');
                                        $('#tip_text').html('云盘资源无法直接播放');
                                        $('#conflict').fadeIn(300, function () {
                                            setTimeout(function () {
                                                $('#conflict').fadeOut(1000);
                                            }, 2000);
                                        });
                                    } else{
                                        window.top.location.href = url;
                                    }
                                } else {
                                    $('#conflict').css('display', 'none');
                                    $('#tip_text').html('该节目已失效');
                                    $('#conflict').fadeIn(300, function () {
                                        setTimeout(function () {
                                            $('#conflict').fadeOut(1000);
                                        }, 2000);
                                    });
                                }
                            } else {
                                // 节目下线提示信息
                                $('#conflict').css('display', 'none');
                                $('#tip_text').html('该节目已下线');
                                $('#conflict').fadeIn(300, function () {
                                    setTimeout(function () {
                                        $('#conflict').fadeOut(1000);
                                    }, 2000);
                                });
                            }
                            return;
                        }
                    }
                );
            }
            ;
            return;
            break;
        default:
            switch(sessionStorage.getItem('pageFrom')){
                case WeChatHelperConstants.DetailPageFrom.MySubScription:
                    upLog(WeChatHelperConstants.LogType.Play,WeChatHelperConstants.LogPlayType.SubScriptionPlay+'_'+sessionStorage.getItem('pagePath')+'_'+pSid+'_'+sSid);
                    break;
                case WeChatHelperConstants.DetailPageFrom.Search:
                    upLog(WeChatHelperConstants.LogType.Play,WeChatHelperConstants.LogPlayType.SearchPlay+'_'+sessionStorage.getItem('pagePath')+'_'+pSid+'_'+sSid);
                    break;
                case WeChatHelperConstants.DetailPageFrom.SubScriptionMore:
                    upLog(WeChatHelperConstants.LogType.Play,WeChatHelperConstants.LogPlayType.SubScriptionPlay+'_'+sessionStorage.getItem('pagePath')+'_'+pSid+'_'+sSid);
                    break;
                case WeChatHelperConstants.DetailPageFrom.WeiXinRecommend:
                    upLog(WeChatHelperConstants.LogType.Play,WeChatHelperConstants.LogPlayType.RecommendPlay+'_'+sessionStorage.getItem('pageFrom')+'_'+pSid+'_'+sSid);
                    break;
                case WeChatHelperConstants.DetailPageFrom.WeiXinSearch:
                    upLog(WeChatHelperConstants.LogType.Play,WeChatHelperConstants.LogPlayType.SubScriptionPlay+'_'+sessionStorage.getItem('pageFrom')+'_'+pSid+'_'+sSid);
                    break;
                case WeChatHelperConstants.DetailPageFrom.AlbumList:
                    upLog(WeChatHelperConstants.LogType.Play,WeChatHelperConstants.LogPlayType.AlbumPlay+'_'+sessionStorage.getItem('pageFrom')+'_'+pSid+'_'+sSid);
                    break;
            }
            break;
    };
//    connectAuthenticate('',WeChatHelperConstants.Action.Play,pSid,sSid,null,null,null,contentType,playType,title);
    var params = {
        eventType : WeChatHelperConstants.EventType.Play,
        pSid : pSid,
        sSid : sSid,
        contentType : contentType,
        playType : playType
    };
    WeChatHelperConstants.CurrentEventType = WeChatHelperConstants.EventType.Play;
    //connectAuthenticate(params,connectAuthenticateCallBack);
    play(params);
}

function searchKey(count){
    WeChatHelperConstants.SearchCurrentPageIndex = 1;
    var keyName = $('#search_key').val();
    if(keyName == ''){
        return;
    }
    var str = encodeURI((keyName));
    WeChatHelperConstants.SearchKey = str;
    setCookie(searchStoreKey,str+','+WeChatHelperConstants.ContentType.ALL);
    $('#loading2').css('display','block');
    WeChatHelperConstants.Loading = true;
    var Para = {
        pageIndex:1,
        keyword:str,
        isHaveCast:true
    };
    clearTimeout(WeChatHelperConstants.CommonAjaxTimer);
    var timeoutFlag = true;
    var timeout = false;
    WeChatHelperConstants.CommonAjaxTimer = setTimeout(function(){
        if(timeoutFlag){
            timeout = true;
            if(!count){
                searchKey(1);
            }else{
                $('#loading').css('display','none');
                $('#loading2').css('display','none');
                WeChatHelperConstants.Loading = false;
            }
        }
    },WeChatHelperConstants.CommonAjaxTimeout);
    commonAjax(SEARCH_URL, Para,
        function (res) {
            if (WeChatHelperConstants.CommonAjaxTimeStamp == Number(this) && res) {
                if (!timeout) {
                    timeoutFlag = false;
                    clearTimeout(WeChatHelperConstants.CommonAjaxTimer);
                    try {
                        $('#loading2').css('display', 'none');
                        WeChatHelperConstants.Loading = false;
                        $('#search_result').html('');
                        var htmlStr = '';
                        $('#search_tab_box').html(htmlStr);
                        res.number_Cast = res.castItems.length;
                        if(res.number_Cast > 0){
                            htmlStr += '<li id="search_tab_cast"><a id="search_count_cast" href="javascript:tabSearch(\'cast\''+',1'+');">'+'导演演员('+res.number_Cast+')'+'</a></li>';
                        }
                        if(res.number_Total > 0){
                            htmlStr += '<li id="search_tab_all"><a id="search_count_all" href="javascript:tabSearch(\'all\''+',1'+');">'+'全部('+res.number_Total+')'+'</a></li>';
                        }
                        if(res.number_Movie > 0){
                            htmlStr += '<li id="search_tab_movie"><a id="search_count_movie" href="javascript:tabSearch(\'movie\''+',1'+');">'+'电影('+res.number_Movie+')'+'</a></li>';
                        }
                        if(res.number_TV > 0){
                            htmlStr += '<li id="search_tab_tv"><a id="search_count_tv" href="javascript:tabSearch(\'tv\''+',1'+');">'+'电视剧('+res.number_TV+')'+'</a></li>';
                        }
                        if(res.number_ZongYi > 0){
                            htmlStr += '<li id="search_tab_zongyi"><a id="search_count_zongyi" href="javascript:tabSearch(\'zongyi\''+',1'+');">'+'综艺('+res.number_ZongYi+')'+'</a></li>';
                        }
                        if(res.number_Comic > 0){
                            htmlStr += '<li id="search_tab_comic"><a id="search_count_comic" href="javascript:tabSearch(\'comic\''+',1'+');">'+'动漫('+res.number_Comic+')'+'</a></li>';
                        }
                        if(res.number_Kids > 0){
                            htmlStr += '<li id="search_tab_kids"><a id="search_count_kids" href="javascript:tabSearch(\'kids\''+',1'+');">'+'少儿('+res.number_Kids+')'+'</a></li>';
                        }
                        if(res.number_JILU > 0){
                            htmlStr += '<li id="search_tab_jilu"><a id="search_count_jilu" href="javascript:tabSearch(\'jilu\''+',1'+');">'+'纪实('+res.number_JILU+')'+'</a></li>';
                        }
                        $('#search_tab_box').html(htmlStr);
                        $('#search_tab_cast').attr('class', '');
                        $('#search_tab_all').attr('class', '');
                        $('#search_tab_movie').attr('class', '');
                        $('#search_tab_tv').attr('class', '');
                        $('#search_tab_zongyi').attr('class', '');
                        $('#search_tab_comic').attr('class', '');
                        $('#search_tab_kids').attr('class', '');
                        $('#search_tab_jilu').attr('class', '');
                        if(res.number_Cast > 0){
                            $('#search_tab_cast').attr('class', 'visited');
                        }else{
                            $('#search_tab_all').attr('class', 'visited');
                        }
                        setCookie(searchTotalKey, res.number_Cast + ',' +res.number_Total + ',' + res.number_Movie + ',' + res.number_TV + ',' + res.number_ZongYi + ',' + res.number_Comic + ',' + res.number_Kids+ ',' + res.number_JILU);
                        WeChatHelperConstants.SearchValues = {};
                        WeChatHelperConstants.SearchValues[WeChatHelperConstants.ContentType.CAST] = [];
                        WeChatHelperConstants.SearchValues[WeChatHelperConstants.ContentType.ALL] = [];
                        WeChatHelperConstants.SearchValues[WeChatHelperConstants.ContentType.MOVIE] = [];
                        WeChatHelperConstants.SearchValues[WeChatHelperConstants.ContentType.TV] = [];
                        WeChatHelperConstants.SearchValues[WeChatHelperConstants.ContentType.ZONGYI] = [];
                        WeChatHelperConstants.SearchValues[WeChatHelperConstants.ContentType.COMIC] = [];
                        WeChatHelperConstants.SearchValues[WeChatHelperConstants.ContentType.KIDS] = [];
                        WeChatHelperConstants.SearchValues[WeChatHelperConstants.ContentType.JILU] = [];
                        var items = res.items;
                        if(res.number_Cast > 0){
                            items = res.castItems;
                        }
                        var str = assembleSearchResultHtml(items,'', true,WeChatHelperConstants.DetailPageFrom.Search);
                        $('#search_result').html(str);
                        var imgArr = $('#search_result').find('.serimg');
                        loadImg(imgArr, getDefaultImgSrc('all'));
//                        var li_num = $(".sifting li").length;
//                        var li_width = Math.max($(".sifting li:eq(0)").outerWidth(),$(".sifting li:eq(1)").outerWidth(),$(".sifting li:eq(2)").outerWidth(),$(".sifting li:eq(3)").outerWidth(),$(".sifting li:eq(4)").outerWidth(),$(".sifting li:eq(5)").outerWidth(),$(".sifting li:eq(6)").outerWidth());
//                        var ul_width = li_width * li_num;
                        var ul_width = $(".sifting li:eq(0)").outerWidth() + $(".sifting li:eq(1)").outerWidth() + $(".sifting li:eq(2)").outerWidth() + $(".sifting li:eq(3)").outerWidth() + $(".sifting li:eq(4)").outerWidth() + $(".sifting li:eq(5)").outerWidth() + $(".sifting li:eq(6)").outerWidth() + $(".sifting li:eq(7)").outerWidth();
                        $(".sifting ul").css("width", ul_width);
                    } catch (e) {
                    };
                }
            }
        }
    );
    upLog(WeChatHelperConstants.LogType.Search,'search_'+str);

};
function tabSearch(tabContentType,pageIndex,searchKey,fromThird,count){
    var initFlag = false;
    if(searchKey){
        initFlag = true;
        WeChatHelperConstants.SearchKey = searchKey;
    }else{
        searchKey = WeChatHelperConstants.SearchKey;
    }
    if(!initFlag && pageIndex != 1){
        $('#loading').css('display','block');
        WeChatHelperConstants.Loading = true;
    } else{
        $('#search_result').html('');
        $('#loading2').css('display','block');
        WeChatHelperConstants.Loading = true;
    }
    setCookie(searchStoreKey,searchKey+','+tabContentType);
    if(pageIndex == 1){
        $('#search_tab_cast').attr('class','');
        $('#search_tab_all').attr('class','');
        $('#search_tab_movie').attr('class','');
        $('#search_tab_tv').attr('class','');
        $('#search_tab_zongyi').attr('class','');
        $('#search_tab_comic').attr('class','');
        $('#search_tab_kids').attr('class','');
        $('#search_tab_jilu').attr('class','');
        $('#search_tab_'+tabContentType).attr('class','visited');
        $('#search_result')[0].scrollTop = 0;
        WeChatHelperConstants.SearchCurrentPageIndex = 1;
    }
    var htmlStr = $('#search_result').html();
    var Para = {
        pageIndex:pageIndex,
        keyword:searchKey
    };
    if(initFlag){
        Para.isHaveCast=true;//微信更所跳转或点击搜索按钮，增加导演演员输出
    }
    if(tabContentType != WeChatHelperConstants.ContentType.ALL){
        Para.contentType = tabContentType;
    }
    clearTimeout(WeChatHelperConstants.CommonAjaxTimer);
    var timeoutFlag = true;
    var timeout = false;
    WeChatHelperConstants.CommonAjaxTimer = setTimeout(function(){
        if(timeoutFlag){
            timeout = true;
            if(!count){
                tabSearch(tabContentType,pageIndex,searchKey,fromThird,1);
            }else{
                $('#loading').css('display','none');
                $('#loading2').css('display','none');
                WeChatHelperConstants.Loading = false;
            }
        }
    },WeChatHelperConstants.CommonAjaxTimeout);
    commonAjax(SEARCH_URL, Para,
        function (res) {
            if (WeChatHelperConstants.CommonAjaxTimeStamp == Number(this) && res) {
                if (!timeout) {
                    timeoutFlag = false;
                    clearTimeout(WeChatHelperConstants.CommonAjaxTimer);
                    $('#loading').css('display', 'none');
                    $('#loading2').css('display', 'none');
                    res.number_Cast = res.castItems.length;
                    if (initFlag) { //从微信更多跳转或按搜索按钮
                        if (fromThird) {//从微信更多跳转
                            $('#search_result').html('');
                            setCookie(searchTotalKey, res.number_Cast + ',' + res.number_Total + ',' + res.number_Movie + ',' + res.number_TV + ',' + res.number_ZongYi + ',' + res.number_Comic + ',' + res.number_Kids+ ',' + res.number_JILU);
                            var tabRuleHtmlStr = '';
                            $('#search_tab_box').html(tabRuleHtmlStr);
                            if(res.number_Cast > 0){
                                tabRuleHtmlStr += '<li id="search_tab_cast"><a id="search_count_cast" href="javascript:tabSearch(\'cast\''+',1'+');">'+'导演演员('+res.number_Cast+')'+'</a></li>';
                            }
                            if(res.number_Total > 0){
                                tabRuleHtmlStr += '<li id="search_tab_all"><a id="search_count_all" href="javascript:tabSearch(\'all\''+',1'+');">'+'全部('+res.number_Total+')'+'</a></li>';
                            }
                            if(res.number_Movie > 0){
                                tabRuleHtmlStr += '<li id="search_tab_movie"><a id="search_count_movie" href="javascript:tabSearch(\'movie\''+',1'+');">'+'电影('+res.number_Movie+')'+'</a></li>';
                            }
                            if(res.number_TV > 0){
                                tabRuleHtmlStr += '<li id="search_tab_tv"><a id="search_count_tv" href="javascript:tabSearch(\'tv\''+',1'+');">'+'电视剧('+res.number_TV+')'+'</a></li>';
                            }
                            if(res.number_ZongYi > 0){
                                tabRuleHtmlStr += '<li id="search_tab_zongyi"><a id="search_count_zongyi" href="javascript:tabSearch(\'zongyi\''+',1'+');">'+'综艺('+res.number_ZongYi+')'+'</a></li>';
                            }
                            if(res.number_Comic > 0){
                                tabRuleHtmlStr += '<li id="search_tab_comic"><a id="search_count_comic" href="javascript:tabSearch(\'comic\''+',1'+');">'+'动漫('+res.number_Comic+')'+'</a></li>';
                            }
                            if(res.number_Kids > 0){
                                tabRuleHtmlStr += '<li id="search_tab_kids"><a id="search_count_kids" href="javascript:tabSearch(\'kids\''+',1'+');">'+'少儿('+res.number_Kids+')'+'</a></li>';
                            }
                            if(res.number_JILU > 0){
                                tabRuleHtmlStr += '<li id="search_tab_jilu"><a id="search_count_jilu" href="javascript:tabSearch(\'jilu\''+',1'+');">'+'纪实('+res.number_JILU+')'+'</a></li>';
                            }
                            $('#search_tab_box').html(tabRuleHtmlStr);
                        } else {
                            var totalArr = [0, 0, 0, 0, 0, 0, 0, 0];
                            try {
                                totalArr = getCookie(searchTotalKey).split(',');
                            } catch (e) {
                            };
                            var tabRuleHtmlStr = '';
                            $('#search_tab_box').html(tabRuleHtmlStr);
                            if(totalArr[0] > 0){
                                tabRuleHtmlStr += '<li id="search_tab_cast"><a id="search_count_cast" href="javascript:tabSearch(\'cast\''+',1'+');">'+'导演演员('+totalArr[0]+')'+'</a></li>';
                            }
                            if(totalArr[1] > 0){
                                tabRuleHtmlStr += '<li id="search_tab_all"><a id="search_count_all" href="javascript:tabSearch(\'all\''+',1'+');">'+'全部('+totalArr[1]+')'+'</a></li>';
                            }
                            if(totalArr[2] > 0){
                                tabRuleHtmlStr += '<li id="search_tab_movie"><a id="search_count_movie" href="javascript:tabSearch(\'movie\''+',1'+');">'+'电影('+totalArr[2]+')'+'</a></li>';
                            }
                            if(totalArr[3] > 0){
                                tabRuleHtmlStr += '<li id="search_tab_tv"><a id="search_count_tv" href="javascript:tabSearch(\'tv\''+',1'+');">'+'电视剧('+totalArr[3]+')'+'</a></li>';
                            }
                            if(totalArr[4] > 0){
                                tabRuleHtmlStr += '<li id="search_tab_zongyi"><a id="search_count_zongyi" href="javascript:tabSearch(\'zongyi\''+',1'+');">'+'综艺('+totalArr[4]+')'+'</a></li>';
                            }
                            if(totalArr[5] > 0){
                                tabRuleHtmlStr += '<li id="search_tab_comic"><a id="search_count_comic" href="javascript:tabSearch(\'comic\''+',1'+');">'+'动漫('+totalArr[5]+')'+'</a></li>';
                            }
                            if(totalArr[6] > 0){
                                tabRuleHtmlStr += '<li id="search_tab_kids"><a id="search_count_kids" href="javascript:tabSearch(\'kids\''+',1'+');">'+'少儿('+totalArr[6]+')'+'</a></li>';
                            }
                            if(totalArr[7] > 0){
                                tabRuleHtmlStr += '<li id="search_tab_jilu"><a id="search_count_jilu" href="javascript:tabSearch(\'jilu\''+',1'+');">'+'纪实('+totalArr[7]+')'+'</a></li>';
                            }
                            $('#search_tab_box').html(tabRuleHtmlStr);
                        }
//                        var li_num = $(".sifting li").length;
//                        var li_width = Math.max($(".sifting li:eq(0)").outerWidth(),$(".sifting li:eq(1)").outerWidth(),$(".sifting li:eq(2)").outerWidth(),$(".sifting li:eq(3)").outerWidth(),$(".sifting li:eq(4)").outerWidth(),$(".sifting li:eq(5)").outerWidth(),$(".sifting li:eq(6)").outerWidth());
//                        var ul_width = li_width * li_num;
                        var ul_width = $(".sifting li:eq(0)").outerWidth() + $(".sifting li:eq(1)").outerWidth() + $(".sifting li:eq(2)").outerWidth() + $(".sifting li:eq(3)").outerWidth() + $(".sifting li:eq(4)").outerWidth() + $(".sifting li:eq(5)").outerWidth() + $(".sifting li:eq(6)").outerWidth() + $(".sifting li:eq(7)").outerWidth();
                        $(".sifting ul").css("width", ul_width);
                        if(pageIndex == 1){
                            $('#search_tab_cast').attr('class','');
                            $('#search_tab_all').attr('class','');
                            $('#search_tab_movie').attr('class','');
                            $('#search_tab_tv').attr('class','');
                            $('#search_tab_zongyi').attr('class','');
                            $('#search_tab_comic').attr('class','');
                            $('#search_tab_kids').attr('class','');
                            $('#search_tab_jilu').attr('class','');
                            if(res.number_Cast > 0){
                                $('#search_tab_cast').attr('class','visited');
                            }else{
                                $('#search_tab_'+tabContentType).attr('class','visited');
                            }
                            $('#search_result')[0].scrollTop = 0;
                        }
                        WeChatHelperConstants.SearchValues = {};
                        WeChatHelperConstants.SearchValues[WeChatHelperConstants.ContentType.CAST] = [];
                        WeChatHelperConstants.SearchValues[WeChatHelperConstants.ContentType.ALL] = [];
                        WeChatHelperConstants.SearchValues[WeChatHelperConstants.ContentType.MOVIE] = [];
                        WeChatHelperConstants.SearchValues[WeChatHelperConstants.ContentType.TV] = [];
                        WeChatHelperConstants.SearchValues[WeChatHelperConstants.ContentType.ZONGYI] = [];
                        WeChatHelperConstants.SearchValues[WeChatHelperConstants.ContentType.COMIC] = [];
                        WeChatHelperConstants.SearchValues[WeChatHelperConstants.ContentType.KIDS] = [];
                        WeChatHelperConstants.SearchValues[WeChatHelperConstants.ContentType.JILU] = [];
                    }
                    var items = res.items;
                    if(tabContentType == WeChatHelperConstants.ContentType.CAST || res.number_Cast > 0){
                        items = res.castItems;
                    }
                    var str = assembleSearchResultHtml(items, '',true,WeChatHelperConstants.DetailPageFrom.Search);
                    if (str) {
                        if (pageIndex == 1) {
                            $('#search_result').html(str);
                        } else {
                            $('#search_result').html(htmlStr + str);
                        }
                        var imgArr = $('#search_result').find('.serimg');
                        loadImg(imgArr, getDefaultImgSrc(tabContentType));
                    }
                    WeChatHelperConstants.Loading = false;
                }
            }
        }
    );
};
/////短视频播放方式
var choosePlay = function(_this){
    $('.hotPlay').not(_this.parent().find('.hotPlay')).css('display','none');
    _this.parent().find('.hotPlay').stop(true,true).fadeIn();
};
function assembleSearchResultHtml(items,content_type,push,from){
    var str = '';
    if(items && items.length > 0){
        for(var i=0; i<items.length; i++){
            var item = items[i];
            var contentType = item.item_contentType;
            if(content_type){
                contentType = content_type;
            }
            if(push){
                WeChatHelperConstants.SearchValues[contentType].push(item);
            }
            var episodeStr = '';
            episodeStr = getSearchEpisodeInfoStr(contentType,item.item_episode,item.item_episodeCount,item.item_score,item.item_duration);
            if(episodeStr != '') {
                if(contentType == WeChatHelperConstants.ContentType.MOVIE){
                    episodeStr = '<div class="shadeMoive"><span>'+episodeStr+'</span></div>';
                }else{
                    episodeStr = '<div class="shade"><span>'+episodeStr+'</span></div>';
                }
            }
            if(contentType == WeChatHelperConstants.ContentType.MOVIE){
                str += '<li><a href="details2.html?from='+from+'&sid='+item.item_sid+'&title='+item.item_title+'"><img class="serimg" src="'+getDefaultImgSrc(contentType)+'" url="'+item.item_icon1+'" /><p class="textShadow2">'+item.item_title+'</p></a>'+episodeStr+'</li>';
            }else if(contentType == WeChatHelperConstants.ContentType.CAST){
                str += '<li><a href="director.html?from='+from+'&name='+item.item_title+'"><img class="serimg" src="'+getDefaultImgSrc(contentType)+'" url="'+item.item_icon1+'" /><p class="textShadow2">'+item.item_title+'</p></a>'+episodeStr+'</li>';
            }else if(contentType == WeChatHelperConstants.ContentType.SHORTVIDEO){
                str += '<li><a href="javascript:void(0);" onclick="choosePlay($(this))"><img class="serimg" src="'+getDefaultImgSrc(contentType)+'" url="'+item.item_icon1+'" /><p class="textShadow2">'+item.item_title+'</p></a>'+episodeStr+'<div class="hotPlay"><a href="javascript:gotoPlay(\''+item.item_sid+'\',\''+item.item_sid+'\',\''+contentType+'\',\''+WeChatHelperConstants.PlayType.Local+'\',\''+item.item_title.replace(/\'/g, "\\\'").replace(/\"/g, "&quot;")+'\');" class="hotLive"></a><a class="hotPush" href="javascript:gotoPlay(\''+item.item_sid+'\',\''+item.item_sid+'\',\''+contentType+'\',\''+WeChatHelperConstants.PlayType.SmallProgram+'\',\''+item.item_title.replace(/\'/g, "\\\'").replace(/\"/g, "&quot;")+'\');"></a><div></li>';
            }else if(contentType == WeChatHelperConstants.ContentType.SPORTS || contentType == WeChatHelperConstants.ContentType.MV || contentType == WeChatHelperConstants.ContentType.XIQU){
                str += '<li><a href="javascript:gotoPlay(\''+item.item_sid+'\',\''+item.item_sid+'\',\''+contentType+'\',\''+WeChatHelperConstants.PlayType.Local+'\',\''+item.item_title.replace(/\'/g, "\\\'").replace(/\"/g, "&quot;")+'\');"><img class="serimg" src="'+getDefaultImgSrc(contentType)+'" url="'+item.item_icon1+'" /><p class="textShadow2">'+item.item_title+'</p></a>'+episodeStr+'</li>';
            }else{
                str += '<li><a href="details.html?from='+from+'&sid='+item.item_sid+'&title='+item.item_title+'"><img class="serimg" src="'+getDefaultImgSrc(contentType)+'" url="'+item.item_icon1+'" /><p class="textShadow2">'+item.item_title+'</p></a>'+episodeStr+'</li>';
            }
        }
    }
    return str;
};
/**
 * 操作权限验证
 * @param pinCode
 * @param action
 * @param pSid
 * @param sSid
 * @param operate
 * @param param
 */
//WeixinJSBridge.call('hideToolbar');
//获取用户网络状态
//network_type:wifi wifi网络
//network_type:edge 非wifi,包含3G/2G
//network_type:fail 网络断开连接
//network_type:wwan（2g或者3g）
function connectAuthenticate(params,callback_fun){
    var type = parseInt(params.type,10);
    try {
        WeChatHelperConstants.WeiXinJSBridge.invoke('getNetworkType', {},
            function (e) {
                if (e.err_msg != 'network_type:wifi') {
                    popNwtWorkAlert();
                    return;
                } else {
                    if(!params.eventType){
                        params.eventType = WeChatHelperConstants.CurrentEventType;
                    }
                    var para = null;
                    var uidflag = false;
                    var clientId = clientId = 'wxsessionid_'+(+new Date());
                    loadingShow();
                    if(params.pin){
                        para = {pin : params.pin};
                    }else{
                        if(params.userid){
                            para = {userid : params.userid};
                            uidflag = true;
                        } else{
                            var cookieUid = getCookie(UIDKey);
                            if (cookieUid) {
                                var _userid = cookieUid.split(',')[0];
                                para = {userid : _userid};
                                uidflag = true;
                            }
                        }
                        if(uidflag){
                            clientId = getCookie(uidPref+para.userid);
                            if(clientId){
                                clientId = clientId.split(',')[3];
                            } else{
                                clientId = 'wxsessionid_'+(+new Date());
                            }
                        }else{
                            clientId = 'wxsessionid_'+(+new Date());
                        }
                    }
                    $("#pin,.prompt_bg").css('display','none');
                    $("#alert,.prompt_bg").css('display','none');
                    clearTimeout(WeChatHelperConstants.timer1);
                    var timeout = true;
                    WeChatHelperConstants.timer1 = setTimeout(function(){
                        if(timeout){
                            console.log('--------------云端校验超时-----------------');
                            toastShow('连接超时，请检查网络');
                            popInputPin();
                            if(params.eventType){
                                if(params.eventType == WeChatHelperConstants.EventType.GetCurrentDevice){
                                    WeChatHelperConstants.CurrentEventType = WeChatHelperConstants.EventType.AddDevice;
                                }else{
                                    WeChatHelperConstants.CurrentEventType = params.eventType;
                                }
                            }
                        }
                    },WeChatHelperConstants.timeout1);
                    commonAjax(AUTHENTICATE_URL,para,function(res){
                            timeout = false;
                            if (!timeout) {
                                clearTimeout(WeChatHelperConstants.timer1);
                                if(res.status < 0){
                                    console.log('--------------云端校验失败-----------------');
                                    // 验证失败，弹出输入PING
                                    $('#conflict').css('display','none');
                                    switch (res.status){
                                        case -1:
                                            $('#tip_text').html('设备码错误，请核对后重试');
                                            break;
                                        case -2:
                                            $('#tip_text').html('验证失败，请重新输入');
                                            break;
                                        case -9:
                                            $('#tip_text').html('验证失败，请重新输入');
                                            break;
                                    }
                                    if(res.status != -3){
                                        $('#conflict').fadeIn(300, function () {
                                            setTimeout(function () {
                                                $('#conflict').fadeOut(1000);
                                            }, 2000);
                                        });
                                    }
                                    popInputPin();
                                    if(params.eventType){
                                        if(params.eventType == WeChatHelperConstants.EventType.GetCurrentDevice){
                                            WeChatHelperConstants.CurrentEventType = WeChatHelperConstants.EventType.AddDevice;
                                        }else{
                                            WeChatHelperConstants.CurrentEventType = params.eventType;
                                        }
                                    }
                                }else{
                                    console.log('--------------云端校验成功-----------------');
                                    $("#pin,.prompt_bg").css('display','none');
                                    $("#alert,.prompt_bg").css('display','none');
                                    if(res.info.ip == '0.0.0.0'){
                                        console.log('--------------云端校验得到ip为0.0.0.0-----------------');
                                        toastShow('无法获取ip地址，请更换设备');
                                        popInputPin();
                                        if(params.eventType){
                                            if(params.eventType == WeChatHelperConstants.EventType.GetCurrentDevice){
                                                WeChatHelperConstants.CurrentEventType = WeChatHelperConstants.EventType.AddDevice;
                                            }else{
                                                WeChatHelperConstants.CurrentEventType = params.eventType;
                                            }
                                        }
                                        return;
                                    }
                                    var ip = 'http://'+res.info.ip;
                                    var port = res.info.port;
                                    var name = res.info.name;
                                    var userid = res.info.userid;
                                    var url = ip+':'+port;
                                    heartbeatUrl = url;//设置心跳url
                                    var info_params = {
                                        ip : ip,
                                        port : port,
                                        name : name,
                                        userid : userid,
                                        clientId : clientId,
                                        url : ip+':'+port
                                    };
                                    var valueStr = info_params.ip+','+info_params.port+','+info_params.name+','+info_params.clientId+','+info_params.url;
                                    storeValue(info_params.userid,valueStr);
                                    WeChatHelperConstants.CurrentDeviceObj = info_params;
                                    if(params.eventType == WeChatHelperConstants.EventType.GetCurrentDevice){
                                        return;
                                    }
                                    if(callback_fun){
                                        callback_fun(params,info_params);
                                    }
                                }
                            }
                        }
                    );
                }
            }
        );
    }catch(e){
        if(!params.eventType){
            params.eventType = WeChatHelperConstants.CurrentEventType;
        }
        var para = null;
        var uidflag = false;
        var clientId = clientId = 'wxsessionid_'+(+new Date());
        loadingShow();
        if(params.pin){
            para = {pin : params.pin};
        }else{
            if(params.userid){
                para = {userid : params.userid};
                uidflag = true;
            } else{
                var cookieUid = getCookie(UIDKey);
                if (cookieUid) {
                    var _userid = cookieUid.split(',')[0];
                    para = {userid : _userid};
                    uidflag = true;
                }
            }
            if(uidflag){
                clientId = getCookie(uidPref+para.userid);
                if(clientId){
                    clientId = clientId.split(',')[3];
                } else{
                    clientId = 'wxsessionid_'+(+new Date());
                }
            }else{
                clientId = 'wxsessionid_'+(+new Date());
            }
        }
        $("#pin,.prompt_bg").css('display','none');
        $("#alert,.prompt_bg").css('display','none');
        clearTimeout(WeChatHelperConstants.timer1);
        var timeout = true;
        WeChatHelperConstants.timer1 = setTimeout(function(){
            if(timeout){
                console.log('--------------云端校验超时-----------------');
                toastShow('连接超时，请检查网络');
                popInputPin();
                if(params.eventType){
                    if(params.eventType == WeChatHelperConstants.EventType.GetCurrentDevice){
                        WeChatHelperConstants.CurrentEventType = WeChatHelperConstants.EventType.AddDevice;
                    }else{
                        WeChatHelperConstants.CurrentEventType = params.eventType;
                    }
                }
            }
        },WeChatHelperConstants.timeout1);
        commonAjax(AUTHENTICATE_URL,para,function(res){
                timeout = false;
                if (!timeout) {
                    clearTimeout(WeChatHelperConstants.timer1);
                    if(res.status < 0){
                        console.log('--------------云端校验失败-----------------');
                        // 验证失败，弹出输入PING
                        $('#conflict').css('display','none');
                        switch (res.status){
                            case -1:
                                $('#tip_text').html('设备码错误，请核对后重试');
                                break;
                            case -2:
                                $('#tip_text').html('验证失败，请重新输入');
                                break;
                            case -9:
                                $('#tip_text').html('验证失败，请重新输入');
                                break;
                        }
                        if(res.status != -3){
                            $('#conflict').fadeIn(300, function () {
                                setTimeout(function () {
                                    $('#conflict').fadeOut(1000);
                                }, 2000);
                            });
                        }
                        popInputPin();
                        if(params.eventType){
                            if(params.eventType == WeChatHelperConstants.EventType.GetCurrentDevice){
                                WeChatHelperConstants.CurrentEventType = WeChatHelperConstants.EventType.AddDevice;
                            }else{
                                WeChatHelperConstants.CurrentEventType = params.eventType;
                            }
                        }
                    }else{
                        console.log('--------------云端校验成功-----------------');
                        $("#pin,.prompt_bg").css('display','none');
                        $("#alert,.prompt_bg").css('display','none');
                        if(res.info.ip == '0.0.0.0'){
                            console.log('--------------云端校验得到ip为0.0.0.0-----------------');
                            toastShow('无法获取ip地址，请更换设备');
                            popInputPin();
                            if(params.eventType){
                                if(params.eventType == WeChatHelperConstants.EventType.GetCurrentDevice){
                                    WeChatHelperConstants.CurrentEventType = WeChatHelperConstants.EventType.AddDevice;
                                }else{
                                    WeChatHelperConstants.CurrentEventType = params.eventType;
                                }
                            }
                            return;
                        }
                        var ip = 'http://'+res.info.ip;
                        var port = res.info.port;
                        var name = res.info.name;
                        var userid = res.info.userid;
                        var url = ip+':'+port;
                        heartbeatUrl = url;//设置心跳url
                        var info_params = {
                            ip : ip,
                            port : port,
                            name : name,
                            userid : userid,
                            clientId : clientId,
                            url : ip+':'+port
                        };
                        var valueStr = info_params.ip+','+info_params.port+','+info_params.name+','+info_params.clientId+','+info_params.url;
                        storeValue(info_params.userid,valueStr);
                        WeChatHelperConstants.CurrentDeviceObj = info_params;
                        if(params.eventType == WeChatHelperConstants.EventType.GetCurrentDevice){
                            return;
                        }
                        if(callback_fun){
                            callback_fun(params,info_params);
                        }
                    }
                }
            }
        );
    }
}
function connectAuthenticateCallBack(params,info_params){
    WeChatHelperConstants.timeout_flag1 = false;
    WeChatHelperConstants.timeout_flag2 = false;
    WeChatHelperConstants.status_flag1 = false;
    WeChatHelperConstants.status_flag2 = false;
    var event_type = params.eventType;
    if(!event_type){
        event_type = WeChatHelperConstants.CurrentEventType;
    }
    var Paras = null;
    var Paras2 = null;
    var pSid = '';
    var sSid = '';
    var contentType = '';
    var playType = params.playType;
    switch(event_type){
        case WeChatHelperConstants.EventType.PinEnterPlay://输入pin码播放
            pSid = params.pSid;
            sSid = params.sSid;
            contentType = params.contentType;
            playType = params.playType;
            if(WeChatHelperConstants.DetailpSid && WeChatHelperConstants.DetailsSid && WeChatHelperConstants.DetailContentType){
                pSid = WeChatHelperConstants.DetailpSid;
                sSid = WeChatHelperConstants.DetailsSid;
                contentType = WeChatHelperConstants.DetailContentType;
                playType = WeChatHelperConstants.DetailPlayType;
            }
            Paras = {
                Action : WeChatHelperConstants.Action.Play,
                clientId :info_params.clientId,
                pSid : pSid,
                sSid : sSid,
                contentType :contentType
            };
            break;
        case WeChatHelperConstants.EventType.Play://直接通过uid验证播放
            pSid = params.pSid;
            sSid = params.sSid;
            contentType = params.contentType;
            playType = params.playType;
            if(WeChatHelperConstants.DetailpSid && WeChatHelperConstants.DetailsSid && WeChatHelperConstants.DetailContentType){
                pSid = WeChatHelperConstants.DetailpSid;
                sSid = WeChatHelperConstants.DetailsSid;
                contentType = WeChatHelperConstants.DetailContentType;
                playType = WeChatHelperConstants.DetailPlayType;
            }
            Paras = {
                Action : WeChatHelperConstants.Action.Play,
                clientId :info_params.clientId,
                pSid : pSid,
                sSid : sSid,
                contentType :contentType
            };
            break;
        case WeChatHelperConstants.EventType.AddDevice://添加设备
            Paras = {
                Action : WeChatHelperConstants.Action.Connect,
                clientId :info_params.clientId
            };
            break;
        case WeChatHelperConstants.EventType.ChangeDevice://切换设备
            if (WeChatHelperConstants.DetailpSid && WeChatHelperConstants.DetailsSid && WeChatHelperConstants.DetailContentType) {
                pSid = WeChatHelperConstants.DetailpSid;
                sSid = WeChatHelperConstants.DetailsSid;
                contentType = WeChatHelperConstants.DetailContentType;
                playType = WeChatHelperConstants.DetailPlayType;
                Paras = {
                    Action: WeChatHelperConstants.Action.Play,
                    clientId: info_params.clientId,
                    pSid: pSid,
                    sSid: sSid,
                    contentType: contentType
                };
            }else{
                Paras = {
                    Action : WeChatHelperConstants.Action.Connect,
                    clientId :info_params.clientId
                };
            }
            break;
        case WeChatHelperConstants.EventType.MobileRemoteControl://遥控器
            Paras = {
                Action : WeChatHelperConstants.Action.PlayControl,
                clientId :info_params.clientId,
                operate : params.operate,
                param : params.param
            };
            Paras2 = params.param2;
            Paras2.Action = WeChatHelperConstants.Action.Event;
            Paras2.clientId = info_params.clientId;
            break;
    };
    clearTimeout(WeChatHelperConstants.timer2);
    var timeoutFlag = true;
    WeChatHelperConstants.timer2 = setTimeout(function(){
        if(timeoutFlag){
            console.log('--------------从云端获取ip后连接超时-----------------');
            switch(event_type){
                case WeChatHelperConstants.EventType.PinEnterPlay://输入pin码播放
                    popAlert();
                    break;
                case WeChatHelperConstants.EventType.Play://直接通过uid验证播放
                    popAlert();
                    break;
                case WeChatHelperConstants.EventType.AddDevice://添加设备
                    popAlert();
                    break;
                case WeChatHelperConstants.EventType.ChangeDevice://切换设备
                    popAlert();
                    break;
                case WeChatHelperConstants.EventType.MobileRemoteControl://遥控器
                    WeChatHelperConstants.timeout_flag1 = true;
                    break;
            };
            WeChatHelperConstants.CurrentEventType = event_type;
            if(event_type != WeChatHelperConstants.EventType.MobileRemoteControl){
                popAlert();
                toastShow('操作超时，请重试!');
            }else{
                if(WeChatHelperConstants.timeout_flag1 && WeChatHelperConstants.timeout_flag2){
                    popAlert();
                    toastShow('操作超时，请重试!');
                }
            }
        }
    },WeChatHelperConstants.timeout2);
    commonAjax(info_params.url,Paras,function(res){
        timeoutFlag = false;
        WeChatHelperConstants.timeout_flag1 = false;
        if (!timeoutFlag) {
            clearTimeout(WeChatHelperConstants.timer2);
            var status = res.status;
            if (status == 1) {
                switch(event_type){
                    case WeChatHelperConstants.EventType.PinEnterPlay://输入pin码播放
                        if(typeof playType != 'undefined' && null != playType){
                            playType = parseInt(playType,10);
                        }
                        $('#loading2').css('display','none');
                        if(playType == WeChatHelperConstants.PlayType.Live){
                            $('#'+currentPlayChannelId).find('.imgPlayIcon').attr('class','imgPlayIcon');
                            currentPlayChannelId = pSid;
                            $('#'+pSid).find('.imgPlayIcon').attr('class','imgPlayIcon playOn');
                            $('#cur').find('.channelProgramPlayIcon').attr('class','channelProgramPlayIcon channelProgramPlayIconOn right');
                        }
                        storeUID(info_params);
                        var valueStr = info_params.ip+','+info_params.port+','+info_params.name+','+info_params.clientId+','+info_params.url;
                        storeValue(info_params.userid,valueStr);
                        window.location.href = './play.html?' + 'pSid=' + escape(pSid) + '&sSid=' + escape(sSid) + '&contentType=' + escape(contentType) + '&playType=' + escape(playType);
                        break;
                    case WeChatHelperConstants.EventType.Play://直接通过uid验证播放
                        $('#loading2').css('display','none');
                        if(typeof playType != 'undefined' && null != playType){
                            playType = parseInt(playType,10);
                        }
                        if(playType == WeChatHelperConstants.PlayType.Live){
                            $('#'+currentPlayChannelId).find('.imgPlayIcon').attr('class','imgPlayIcon');
                            currentPlayChannelId = pSid;
                            $('#'+pSid).find('.imgPlayIcon').attr('class','imgPlayIcon playOn');
                            $('#cur').find('.channelProgramPlayIcon').attr('class','channelProgramPlayIcon channelProgramPlayIconOn right');
                        }
                        storeUID(info_params);
                        var valueStr = info_params.ip+','+info_params.port+','+info_params.name+','+info_params.clientId+','+info_params.url;
                        storeValue(info_params.userid,valueStr);
                        window.location.href = './play.html?' + 'pSid=' + escape(pSid) + '&sSid=' + escape(sSid) + '&contentType=' + escape(contentType) + '&playType=' + escape(playType);
                        break;
                    case WeChatHelperConstants.EventType.AddDevice://添加设备
                        storeUID(info_params,true);
                        var valueStr = info_params.ip+','+info_params.port+','+info_params.name+','+info_params.clientId+','+info_params.url;
                        storeValue(info_params.userid,valueStr);
                        refreshDevices();
                        break;
                    case WeChatHelperConstants.EventType.ChangeDevice://切换设备
                        storeUID(info_params);
                        var valueStr = info_params.ip+','+info_params.port+','+info_params.name+','+info_params.clientId+','+info_params.url;
                        storeValue(info_params.userid,valueStr);
                        refreshDevices();
                        var uids = getCookie(UIDKey);
                        if(uids){
                            var current_uid = uids.split(',')[0];
                            var infos = getCookie(uidPref+current_uid);
                            if (infos) {
                                var infoArr = infos.split(',');
                                if (infoArr.length > 0) {
                                    WeChatHelperConstants.CurrentDeviceObj = {
                                        ip: infoArr[0],
                                        port: infoArr[1],
                                        name: infoArr[2],
                                        userid: current_uid,
                                        clientId: infoArr[3],
                                        url: infoArr[0] + ':' + infoArr[1]
                                    }
                                }
                            }
                        }
                        break;
                    case WeChatHelperConstants.EventType.MobileRemoteControl://遥控器
                        break;
                };
            } else {
                WeChatHelperConstants.status_flag1 = true;
                if (WeChatHelperConstants.status_flag1 && WeChatHelperConstants.status_flag2) {
                    $('#loading2').css('display', 'none');
                    toastShow('设备正被其它终端控制，请重新推送播放');
                }
            }
        }
    });
    if(event_type == WeChatHelperConstants.EventType.MobileRemoteControl){
        clearTimeout(WeChatHelperConstants.timer3);
        var timeoutFlag2 = true;
        WeChatHelperConstants.timer3 = setTimeout(function(){
            if(timeoutFlag2){
                console.log('--------------从云端获取ip后连接超时2-----------------');
                WeChatHelperConstants.timeout_flag2 = true;
                WeChatHelperConstants.status_flag2 = true;
                WeChatHelperConstants.CurrentEventType = event_type;
                if(WeChatHelperConstants.timeout_flag1 && WeChatHelperConstants.timeout_flag2){
                    popAlert();
                    toastShow('操作超时，请重试!');
                }
            }
        },WeChatHelperConstants.timeout3);
        commonAjax(info_params.url,Paras2,function(res){
            timeoutFlag2 = false;
            WeChatHelperConstants.timeout_flag2 = false;
            if (!timeoutFlag2) {
                clearTimeout(WeChatHelperConstants.timer3);
                var status = res.status;
                if (status == 1) {

                } else {
                    WeChatHelperConstants.status_flag2 = true;
                    if (WeChatHelperConstants.status_flag1 && WeChatHelperConstants.status_flag2) {
                        $('#loading2').css('display', 'none');
                        toastShow('设备正被其它终端控制，请重新推送播放');
                    }
                }
            }
        });
    }
}
function loadingShow(){
    var h = getScrollHeight();
    var top = getScrollTop() + 120;
    $('#loading2').css({'height':h+'px','display':'block'});
    $('#loading2 .loadingImg').css('top',top+'px');
    $('#loading2 .loadingtext').css('top',(top+10)+'px');
};
function cancelLoadingShow(){
    $('#loading2').css({'display':'none'});
}
function toastShow(text){
    $('#loading2').css('display', 'none');
    $('#conflict').css('display', 'none');
    $('#tip_text').html(text);
    $('#conflict').fadeIn(300, function () {
        setTimeout(function () {
            $('#conflict').fadeOut(1000);
        }, 2000);
    });
}
function popInputPin(){
    $('#loading2').css('display','none');
    $('#alert').css('display','none');
    var top = getScrollTop();
    var height = getScrollHeight();
    $('#pin').css('top',parseInt(top+30)+'px');
    $('.prompt_bg').css('height',height+'px');
    $("#pin,.prompt_bg").css('display','block');
}
function cancelInputPin(){
    $("#pin,.prompt_bg").css('display','none');
}
function tryPushPlay(){
    connectAuthenticate('','',null,null,null,null);
}
function popAlert(){
    $('#loading2').css('display','none');
    var top = getScrollTop();
    var height = getScrollHeight();
    $('#alert').css('top',parseInt(top+30)+'px');
    $('.prompt_bg').css('height',height+'px');
    $("#alert,.prompt_bg").css('display','block');
}
function cancelAlert(){
    $("#alert,.prompt_bg").css('display','none');
}
function popNwtWorkAlert(){
    $('#loading2').css('display','none');
    var top = getScrollTop();
    var height = getScrollHeight();
    $('#network_alert').css('top',parseInt(top+30)+'px');
    $('.prompt_bg').css('height',height+'px');
    $("#network_alert,.prompt_bg").css('display','block');
}
function cancelNetWorkAlert(){
    $("#network_alert,.prompt_bg").css('display','none');
}
/**
 * 播控操作
 * @param operate
 * @param param
 */
function wxPlayControl(operate,param){
    connectAuthenticate(null,WeChatHelperConstants.Action.PlayControl,null,null,operate,param);
}
/**
 * 播放页【播放】/【暂停】按钮点击事件
 */
function playPause(){
    if($('#playStatus_icon').hasClass('playing')){
        wxPlayControl(WeChatHelperConstants.WeChatOperate.pause,0);
    }else{
        wxPlayControl(WeChatHelperConstants.WeChatOperate.play,0);
    }
}
/**
 * 从中间件获取参数实时刷新播放页UI
 * @param second
 * @param totalSecond
 * @param volumn
 * @param playStatus
 */
function refreshPlayUI(second,totalSecond,volumn,playStatus){
    try{
        second = parseInt(second);
        if(isNaN(second)){
            second = 0;
        }
    } catch(e){
        second = 0;
    }
    try{
        totalSecond = parseInt(totalSecond);
        if(isNaN(totalSecond)){
            totalSecond = 0;
        }
    } catch(e){
        totalSecond = 0;
    }
    try{
        volumn = parseInt(volumn);
        if(isNaN(volumn)){
            volumn = 0;
        }
    } catch(e){
        volumn = 0;
    }
    if(volumn <0){
        volumn = 0;
    }
    if(volumn >7){
        volumn = 7;
    }
    try{
        playStatus = parseInt(playStatus);
        if(isNaN(playStatus)){
            playStatus = WeChatHelperConstants.PlayingStatus;
        }
    } catch(e){
        playStatus = WeChatHelperConstants.PlayingStatus;
    }
    var nL = parseInt((second/totalSecond)*progressWidth)-23;
    $('#progress_point').css('left', nL + 'px');
    var percentage = parseFloat(second/totalSecond).toFixed(2);
    $('#play_time_tag').css('left', (nL+23) + 'px').html(secondToTimeFormat2(second));
    $('#progressbar_on').css('width',percentage*100+'%');

    var nT = parseInt(((7-volumn)/7)*volumnProgressHeight)-24;
    $('#volumn_progress_point').css('top', nT + 'px');
    var percentage = parseFloat(volumn/7).toFixed(2);
    $('#volumn_progressbar_on').css('height',100*percentage+'%');
    if(volumn <= 0){
        $('#play_volumn_icon').attr('class','volumeOff');
    }else{
        $('#play_volumn_icon').attr('class','volumeOn');
    }
    switch(playStatus){
        case WeChatHelperConstants.PlayingStatus:
            $('#playStatus_icon').attr('class','topLeft playing');
            break;
        case WeChatHelperConstants.PauseStatus:
            $('#playStatus_icon').attr('class','topLeft pause');
            break;
    };
    $('#total_time').html(secondToTimeFormat(totalSecond));
};
/*
function pinEnter(){
    var pinCode = $('#pin_code').val();
    if(pinCode != ''){
        //connectAuthenticate(pinCode,'',null,null,null,null);
        var params = {
            eventType:WeChatHelperConstants.CurrentEventType,
            pin:pinCode
        };
        pinCodeConnect(pinCode,function(device){
            if(WeChatHelperConstants.CurrentEventType == WeChatHelperConstants.EventType.Play){
                if()
            }

        });
        connectAuthenticate(params,connectAuthenticateCallBack);
    }else{
        $('#conflict').css('display','none');
        $('#tip_text').html('请输入设备码');
        $('#conflict').fadeIn(300,function(){
            setTimeout(function(){
                $('#conflict').fadeOut(1000);
            },1500);
        });
    }
}
*/
/*
function refreshDevices(){
    var deviceHtmlStr = '';
    var uids = getCookie(UIDKey);
    if (uids) {
        var uidsArr = uids.split(',');
        for (var i = 0; i < uidsArr.length; i++) {
            if (i == 6) {
                break;
            }
            var info = getCookie(uidPref+uidsArr[i]).split(',');
            var name = info[2];
            if (i == 0) {
                heartbeatUrl = info[4];
                $('#selectTv').html('<span>'+name+'</span><i></i>');
//                deviceHtmlStr += '<li id="' + uidsArr[i].replace(uidPref, '') + '" class="on"><i class="tv"></i><span>' + name + '</span></li>';
            } else {
                deviceHtmlStr += '<li id="' + uidsArr[i].replace(uidPref, '') + '" class="tv"><i class="tv">&nbsp;</i><span>' + name + '</span></li>';
            }
        }
    }
    deviceHtmlStr += '<li id="addBoxes"><i class="add">&nbsp;</i><span>添加新设备</span></li>';
    $('#mydevices').html(deviceHtmlStr);
    bindDeviceChangeEvent();
};
*/

function bindDeviceChangeEvent(){
    $('#mydevices li').click(function(){
        var urls = WeChatHelperConstants.PlayUrls;
        var userid = $(this).attr('id');
        if(userid != 'addBoxes'){
            $(this).addClass("on");
            $(this).siblings().removeClass("on");
        }
        if(userid != 'addBoxes'){
            $(".deviceBox").slideUp(300);
            var curInfos = getCookie(UIDKey);
            if(curInfos){
                var curuserid = curInfos.split(',')[0];
                if(curuserid == userid){
                    return;
                }
            };
            var params = {
                eventType:WeChatHelperConstants.EventType.ChangeDevice,
                userid:userid
            };
            WeChatHelperConstants.CurrentEventType = WeChatHelperConstants.EventType.ChangeDevice;
            connectAuthenticate(params,connectAuthenticateCallBack);
            /*
            if(urls.pSid && urls.sSid){
                connectAuthenticate('',WeChatHelperConstants.Action.Play,urls.pSid,urls.sSid,null,null,userid,urls.contentType,urls.playType,null);
            }else{
                connectAuthenticate('','','','',null,null,userid,'',WeChatHelperConstants.PlayType.LargeProgram,null);
            }
            */
        }else{
            $("#pin,.prompt_bg").fadeIn(300);
            WeChatHelperConstants.CurrentEventType = WeChatHelperConstants.EventType.AddDevice;
        }
    });
}
function moreTVHelperShowOrHide(){
    if(browser.versions.ios){
        return false;
    }
    var timestamp = (+new Date());
    var timeCookie = getCookie(timeStampKey);
    var flagCookie = getCookie(showHideFlagKey);
    if(!timeCookie && !flagCookie){
        setCookie(timeStampKey,timestamp);
        setCookie(showHideFlagKey,'1');
        return true;
    }else{
        if(timestamp -parseInt(timeCookie) >24*60*60*1000){
            setCookie(timeStampKey,timestamp);
            setCookie(showHideFlagKey,'1');
            return true;
        } else{
            if(flagCookie == 1){
                return true;
            } else{
                return false;
            }
        }
    }

};
function hideMoreTVHelper(){
    setCookie(showHideFlagKey,'-1');
    $(".header").removeClass("header2");
    $(".moreTv").slideUp(300);
};
function searchInputChange(type){
    var val = document.getElementById('search_key').value;
    if(val.length>0){
        $("#delete_key").css('display','block');
    }else{
        $('#delete_key').css('display','none');
    }
};
function searchKeyClear(){
    document.getElementById('search_key').value = '';
    $('#delete_key').css('display','none');
};
function upLog(type,logStr){
    console.log('上传日志：'+type+' 【'+logStr+'】');
    try{
        var uid = 'unKnow';
        var addRess = 'http://0.0.0.0:0';
        var deviceName = 'unKnow';
        var userIds = getCookie(UIDKey);
        if(userIds){
            uid = userIds.split(',')[0].replace(uidPref,'');
            var info = getCookie(uidPref+uid);
            if(info){
                var infoArr = info.split(',');
                addRess = infoArr[4];
                deviceName = infoArr[2];
            }
        }
        var userName = getCookie('userName');
        var Para = {};
        switch(type){
            case WeChatHelperConstants.LogType.Play:
                Para = {
                    log : type,
                    path : logStr,
                    userid : userName,
                    deviceId : uid,
                    deviceName : deviceName,
                    deviceIp : addRess,
                    logversion : '001',
                    version : Version
                };
                break;
            default :
                Para = {
                    log : type,
                    key : logStr,
                    userid : userName,
                    logversion : '001',
                    version : Version
                };
                break;
        }
        commonAjaxForUpLog(UpLogUrl,Para,function(){

        });
    }catch(e){
        console.log('Upload Log Exception');
    }
}

(function($){
    $.fn.msclick = function(header,content,visited,callback){
        $(header).each(function(index){
            $(this).attr("headerindex",index+"h")
            $(header).click(function(){
                var headers  = parseInt($(this).attr("headerindex"));
                $(this).addClass(visited);
                $(header).not($(this)).removeClass(visited);
                $(content).eq(headers).stop(true,true).slideDown(0);
                $(content).not($(content).eq(headers)).slideUp(0);

            });
            if(callback){
                callback();
            }
        });

    }
})(jQuery);
$(function(){
    /////////////////pin码输入
    $(".pin input").focus(function(){
        $(this).addClass("blue");
        if($(this).val() == '请输入设备码'){
            $(this).val("");
        }
    });
    $('#search_key').keyup(function(){
        searchInputChange('2');
    });



    //////设备冲突
    $("#controlBoxes a").click(function(){
        $(".prompt_bg,.prompt").fadeOut(300);
    });
	//////////////广告位关闭
	$(".moreTv .close").click(function(){
        hideMoreTVHelper();
        setCookie(timeStampKey,99999999999999);
        setCookie(showHideFlagKey,'-1');
	});
    $(".moreTv .install").click(function(){
        hideMoreTVHelper();
        window.location.href = 'http://portal.moretv.com.cn/mportal/down/index.html';
    });
	////选择我的设备
	$("#boxesBtn").click(function(event){
        var display = $('#myBoxes').css('display');
        if(display == 'block'){
            $("#myBoxes").slideUp(300);
        }else{
		    $("#myBoxes").slideDown(300);
        }
		$(".playSelections .content").fadeOut(300);
		event.stopPropagation();
		$(document).click(function(e){
            if(e.currentTarget.id != 'addBoxes'){
			    $("#myBoxes").slideUp(300);
            }
		});
	});

	///////添加新设备
    /*
	$(document).on("click","#addBoxes",function(){
		$("#pin,.prompt_bg").css('display','block');
	});
	*/
    $('.prompt_bg,#pin .close,#pin .cancel').click(function(){
        $("#pin,.prompt_bg").css('display','none');
    });
    $('.prompt_bg,#alert .close').click(function(){
        $("#alert,.prompt_bg").css('display','none');
    });
    $('.prompt_bg,#network_alert .close').click(function(){
        $("#network_alert,.prompt_bg").css('display','none');
    });

    ////tab切换内容
    //$(".push2").msclick(".push2 li",".episodes","visited")
    $('.push2 li').click(function(){
        var item = $(this).attr('id').slice(-1);
        $('.push2').find('li').attr('class','');
        $(this).attr('class','visited');
        if(item == '0' || item == '1'){
            $('.episodes').eq(0).css('display','block');
            $('.episodes').eq(1).css('display','none');
        }else{
            $('.episodes').eq(0).css('display','none');
            $('.episodes').eq(1).css('display','block');
        }
    });
});

var currentChannelId='';
var date1RowCount=0;
var date2RowCount=0;
var date3RowCount=0;
var preCount = 0;
var channelListScrollTop=0;
var channelGroupScrollLeft=0;
var currentPlayChannelId='';
function showPrograms(_sid,_id){
    $('#'+currentChannelId).find('.channelListRightSide').attr('class','channelListRightSide');
    $('#'+_id).find('.channelListRightSide').attr('class','channelListRightSide channelListRightSideOn');
    currentChannelId = _id;
    var htmlStr = '';
    if (_sid) {
        $('#channel_program_box').html('');
        commonAjax(CHNNEL_PROGRAMS_LIST_URL, {sid:_sid}, function (res) {
            $('#loading2').css('display', 'none');
            var cflag = false;
            var date = new Date().format('yyyy-MM-dd HH:mm');
            var currentTime = parseInt((date.toString().split(' ')[1].replace(':','')), 10);
            if(res && res.status && res.status=='200' && res.ChannelList && res.ChannelList.length>0 && res.ChannelList[0].channelItems && res.ChannelList[0].channelItems.length>0){
                $('#title_name').html(res.ChannelList[0].station);
                var channelGroupItems = res.ChannelList[0].channelItems;
                if(channelGroupItems[2] && channelGroupItems[2].items && channelGroupItems[2].items.length>0){
                    var items1 = channelGroupItems[2].items;
                    date1RowCount = items1.length;
                    for(var i=0; i<date1RowCount;i++){
                        htmlStr += '<div class="channelProgramItem">'
                            +'<div class="channelProgramTime channelTextDone">'+items1[i].beginTime+'</div>'
                            +'<div class="channelProgramPlayIconSpace right"></div>'
                            +'<div class="channelProgramTitle"><span class="channelProgramTitleText channelTextDone">'+items1[i].title+'</span></div>'
                            +'</div>';
                    }
                }
                if(channelGroupItems[1] && channelGroupItems[1].items && channelGroupItems[1].items.length>0){
                    var items2 = channelGroupItems[1].items;
                    date2RowCount = items2.length;
                    var tempCount = 0;
                    for(var j=0; j<date2RowCount;j++){
                        if(!cflag){
                            var time = items2[j].beginTime.toString();
                            time = parseInt(time.replace(':', ''), 10);
                            if (currentTime >= time) {
                                preCount = tempCount;
                                if(currentPlayChannelId == _id){
                                    htmlStr += '<div class="channelProgramItem" id="cur">'
                                        +'<div class="channelProgramTime channelProgramCurrentTime">正在播</div>'
                                        +'<div class="channelProgramPlayIcon channelProgramPlayIconOn right"></div>'
                                        +'<div class="channelProgramTitle"><span class="channelProgramTitleText">'+items2[j].title+'</span></div>'
                                        +'</div>';
                                }else{
                                    htmlStr += '<div class="channelProgramItem" id="cur">'
                                        +'<div class="channelProgramTime channelProgramCurrentTime">正在播</div>'
                                        +'<div class="channelProgramPlayIcon right" onclick="gotoPlay(\''+_id+'\',\''+_sid+'\',\'live\',\''+WeChatHelperConstants.PlayType.Live+'\');"></div>'
                                        +'<div class="channelProgramTitle"><span class="channelProgramTitleText">'+items2[j].title+'</span></div>'
                                        +'</div>';
                                }
                                cflag = true;
                            }else {
                                htmlStr += '<div class="channelProgramItem">'
                                    +'<div class="channelProgramTime">'+items2[j].beginTime+'</div>'
                                    +'<div class="channelProgramPlayIconSpace right"></div>'
                                    +'<div class="channelProgramTitle"><span class="channelProgramTitleText">'+items2[j].title+'</span></div>'
                                    +'</div>';
                            }
                        } else {
                            htmlStr += '<div class="channelProgramItem">'
                                +'<div class="channelProgramTime channelTextDone">'+items2[j].beginTime+'</div>'
                                +'<div class="channelProgramPlayIconSpace right"></div>'
                                +'<div class="channelProgramTitle"><span class="channelProgramTitleText channelTextDone">'+items2[j].title+'</span></div>'
                                +'</div>';
                        }
                        tempCount++;
                    }
                }
                if(channelGroupItems[0] && channelGroupItems[0].items && channelGroupItems[0].items.length>0){
                    var items3 = channelGroupItems[0].items;
                    date3RowCount = items3.length;
                    for(var k=0; k<date3RowCount;k++){
                        htmlStr += '<div class="channelProgramItem">'
                            +'<div class="channelProgramTime">'+items3[k].beginTime+'</div>'
                            +'<div class="channelProgramPlayIconSpace right"></div>'
                            +'<div class="channelProgramTitle"><span class="channelProgramTitleText">'+items3[k].title+'</span></div>'
                            +'</div>';
                    }
                }
                $('#channel_program_box').html(htmlStr);
                $('#channel_program_box').find('.channelProgramItem').each(function(index){
                    var totalWidth = $(this).width();
                    var timeWidth = $(this).find('.channelProgramTime').width();
                    var rightWidth = $(this).find('.right').width()+15;
                    var availableTextWidth = totalWidth-timeWidth-rightWidth-15;
                    var textWidth = $(this).find('.channelProgramTitleText').width();
                    if(textWidth>availableTextWidth){
                        $(this).find('.channelProgramTitle').attr('class','channelProgramTitle channelProgramTitle2');
                    }
                });
                var scrollRow = date1RowCount + preCount;
                document.body.scrollTop = $('#channel_program_box').find('.channelProgramItem').eq(0).height() * (scrollRow);
                if((!channelGroupItems[0].items || channelGroupItems[0].items.length<=0) && (!channelGroupItems[1].items || channelGroupItems[1].items.length<=0) && (!channelGroupItems[2].items || channelGroupItems[2].items.length<=0)){
                    $('#channel_program_box').html('<div class="noPrograms">抱歉，该频道暂未提供节目单</div>');
                }
            }
        });
    }

};
function changeChannelProgramsListPos(type){
    switch(type){
        case 1:
            document.body.scrollTop = 0;
            break;
        case 2:
            var scrollRow = date1RowCount + preCount;
            document.body.scrollTop = $('#channel_program_box').find('.channelProgramItem').eq(0).height() * (scrollRow);
            break;
        case 3:
            document.body.scrollTop = $('#channel_program_box').find('.channelProgramItem').eq(0).height() * (date1RowCount+date2RowCount+1);
            break;
    }
}

function makeDirectorDetail(name){
    var url = PERSON_DETAIL_URL + name + '/40?callback=?';
    commonAjax(url,null,function(res){
        $('#loading2').css('display','none');
        if(res && res.status=='200'){
            if(res.metadata){
                var md = res.metadata;
//                $('#title_name').html(md.actor);
                $('#birthday').html(md.birthday);
                $('#hometown').html(md.hometown);
                $('#job').html(md.job);
                $('#person_pic').attr('url',md.image);
                var imgArr = $('#person_pic');
                loadImg(imgArr,getDefaultImgSrc(WeChatHelperConstants.DefaultImgBgType.Person));
                if(res.metadata.honor && res.metadata.honor.length>0){
                    var count = 0;
                    var htmlStr = '<ul>';
                    for(var i=0; i<res.metadata.honor.length; i++){
                        if(res.metadata.honor[i]){
                            count++;
                            if (count <= 2) {
                                htmlStr += '<li><div class="icon">&nbsp;</div><div class="text">' + res.metadata.honor[i] + '</div></li>';
                                if (count == 2) {
                                    htmlStr += '</ul>';
                                }
                            }else{
                                if (count == 3) {
                                    htmlStr += '<ul id="honorMore" style="display:none;">';
                                }
                                htmlStr += '<li><div class="icon">&nbsp;</div><div class="text">' + res.metadata.honor[i] + '</div></li>';
                            }
                        }
                    }
                    if(count != 2){
                        htmlStr += '</ul>';
                    }
                    $('#honor').html(htmlStr);
                    if(count>2){
                        $('#honorBtn').css('display','block');
                    }
                }
                if(res.items && res.items.length>0){
                    var htmlStr2 = '<ul>';
                    htmlStr2 += assembleSearchResultHtml(res.items,null,false,WeChatHelperConstants.DetailPageFrom.Search);
                    htmlStr2 += '</ul>';
                    $('#programs_list').html(htmlStr2);
                    var imgArr = $('#programs_list').find('img');
                    loadImg(imgArr,getDefaultImgSrc(WeChatHelperConstants.ContentType.ALL));
                }

            }
        }
    });

}
/**
 * 初始化我的订阅所有可订阅栏目列表，订阅树保存在本地js/rss_site.json。
 * 全局变量 WeChatHelperConstants.SubScriptionTree 保存订阅树map结构
 */
function assembleSubScriptionList(){
    $.getJSON('js/rss_site.json',function(res){
        if (res && res.children && res.children.length>0) {
            WeChatHelperConstants.SubScriptionTree = [];
            var tagsHtmlStr = '';
            var contentHtmlStr = '';
            for (var i = 0; i < res.children.length; i++){
                var tagObj = {};
                var groupCode = res.children[i].code;
                var groupName = res.children[i].name;
                var groupContentType = res.children[i].contentType;
                tagObj.groupCode = groupCode;
                tagObj.groupName = groupName;
                tagObj.groupContentType = groupContentType;
                tagObj.items = [];
                if(i == 0){
                    tagsHtmlStr += '<a idx="'+i+'" href="javascript:void(0);" class="visited">'+groupName+'</a>';
                }else{
                    tagsHtmlStr += '<a idx="'+i+'" href="javascript:void(0);">'+groupName+'</a>';
                }
                if(res.children[i].children && res.children[i].children.length>0){
                    if(i == 0){
                        contentHtmlStr += '<ul id="'+groupCode+'" contentType="'+groupContentType+'">';
                    }else{
                        contentHtmlStr += '<ul id="'+groupCode+'" contentType="'+groupContentType+'" style="display:none;">';
                    }
                    for(var j=0; j<res.children[i].children.length; j++){
                        var itemName = res.children[i].children[j].name;
                        var itemCode = res.children[i].children[j].code;
                        var itemType = res.children[i].children[j].type;
                        var itemIcon1 = res.children[i].children[j].icon1;
                        var itemTemplateCode = res.children[i].children[j].templateCode;
                        var itemContentType = groupContentType;
                        if(res.children[i].children[j].contentType){
                            itemContentType = res.children[i].children[j].contentType;
                        }
                        var itemObj = {};
                        itemObj.itemName = itemName;
                        itemObj.itemCode = itemCode;
                        itemObj.itemType = itemType;
                        itemObj.itemIcon1 = itemIcon1;
                        itemObj.itemTemplateCode = itemTemplateCode;
                        itemObj.itemContentType = itemContentType;
                        tagObj.items.push(itemObj);
                        contentHtmlStr += '<li id="' + groupCode + subScriptionSeparate + itemCode + '" name="' + itemName + '" code="' + itemCode + '" type="' + itemType + '" templateCode="' + itemTemplateCode + '" contentType="' + itemContentType + '">'
                            + '<div class="imgBox"><img class="imgicon" src="' + getDefaultImgSrc(WeChatHelperConstants.DefaultImgBgType.SubScriptionIcon) + '" url="img/subscription/' + groupCode + '/' + itemName + '.jpg" /></div>'
                            + '<i class="select">&nbsp;</i>'
                            + '<div class="text">'
                            + '<span>' + itemName + '</span>'
                            + '</div>'
                            + '</li>';
                    }
                    contentHtmlStr += '</ul>';
                    WeChatHelperConstants.SubScriptionTree.push(tagObj);
                }
            }
            $('#subscription_group_tag').html(tagsHtmlStr);
            $('#mySubscription').html(contentHtmlStr);
            var imgArr = $('#mySubscription').find('ul').eq(0).find('img');
            loadImg(imgArr,getDefaultImgSrc(WeChatHelperConstants.DefaultImgBgType.SubScriptionIcon));
            initSubScription();
            // 绑定左侧分组点击切换事件
            $('#subscription_group_tag').find('a').click(function(){
                document.body.scrollTop = 0;
                var _idx = parseInt($(this).attr('idx'),10);
                $('#subscription_group_tag').find('a').each(function(index){
                    if(index != _idx){
                        $(this).attr('class','');
                    }
                });
                $(this).attr('class','visited');
                $('#mySubscription').find('ul').each(function(index){
                    if(index != _idx){
                        $(this).css('display','none');
                    }else{
                        $(this).css('display','block');
                        var imgArr = $('#mySubscription').find('ul').eq(index).find('img');
                        loadImg(imgArr,getDefaultImgSrc(WeChatHelperConstants.DefaultImgBgType.SubScriptionIcon));
                    }
                });
            });
            // 绑定每一个订阅标签点击事件
            $("#mySubscription").delegate("li","click",function(){
                var _content_type = $(this).attr('contenttype');
                var _code = $(this).attr('code');
//                $(this).toggleClass("selected");
                $('#tag_'+_content_type+subScriptionSeparate+_code).toggleClass("selected");
                $('#tag_top'+subScriptionSeparate+_code).toggleClass("selected");
            });
        }
    });
};
function itemCodeIsExists(item_code){
    for(var i=0; i<WeChatHelperConstants.SubScriptionTree[0].items.length; i++){
        if(item_code == WeChatHelperConstants.SubScriptionTree[0].items[i].itemCode){
            return true;
            break;
        }
    }
    return false;
}
/**
 * 初始化我的订阅页面，初始化本地保存的已订阅标签，勾选状态
 * [group code]-[item code]-[type]-[contentType]-[templateCode]-[name]
 * eg: subscription-tag_hot=tag_top-movie_hot-0-movie-0-院线大片,tag_top-movie_hollywood-0-movie-0-好莱坞巨制
 */
function initSubScription(){
    $('#mySubscription').find('ul').each(function(){
        var group_id = $(this).attr('id');
        var subs_ids = getCookie(subScriptionPrefix+group_id);
        var codeArr = [];
        if(subs_ids){
            var ids_arr = subs_ids.split(',');
            for(var i=0; i<ids_arr.length; i++){
                var code = ids_arr[i].split(subScriptionSeparate)[1];
                codeArr.push(code);
            }
            if(codeArr.length>0){
                $(this).find('li').each(function(){
                    for(var k=0; k<codeArr.length;k++){
                        if($(this).attr('id') == (group_id+subScriptionSeparate+codeArr[k])){
                            var _content_type = $(this).attr('contenttype');
                            $('#tag_'+_content_type+subScriptionSeparate+codeArr[k]).toggleClass("selected");
                            $('#tag_top'+subScriptionSeparate+codeArr[k]).toggleClass("selected");
                        }
                    }
                });
            }

        }
    });
};
/**
 * 保存用户选择的订阅标签到本地
 * [group code]-[item code]-[type]-[contentType]-[templateCode]-[name]
 * eg: subscription-tag_hot=tag_top-movie_hot-0-movie-0-院线大片,tag_top-movie_hollywood-0-movie-0-好莱坞巨制
 */
function saveSubScription() {
    for (var i = 0; i < subScriptionGroupType.length; i++) {
        setCookie(subScriptionPrefix + subScriptionGroupType[i], '');
    }
    $('#mySubscription').find('ul').each(function (index) {
        var group_id = $(this).attr('id');
        var subs_ids = [];
        var subs_ids_str = '';
        $(this).find('li').each(function () {
            var templatecode = $(this).attr('templatecode');
            if (!templatecode) {
                templatecode = '0';
            }
            var type = $(this).attr('type');
            var code = $(this).attr('code');
            var contentType = $(this).attr('contenttype');
            if (index > 0) {
                if ($('#tag_top' + subScriptionSeparate + code).length > 0) {

                } else {
                    if ($(this).attr('class') == 'selected') {
                        subs_ids.push(group_id + subScriptionSeparate + code + subScriptionSeparate + type + subScriptionSeparate + contentType + subScriptionSeparate + templatecode + subScriptionSeparate + $(this).find('span').html());
                    }
                }
            } else {
                if ($(this).attr('class') == 'selected') {
                    subs_ids.push(group_id + subScriptionSeparate + code + subScriptionSeparate + type + subScriptionSeparate + contentType + subScriptionSeparate + templatecode + subScriptionSeparate + $(this).find('span').html());
                }
            }
        });
        if (subs_ids.length > 0) {
            subs_ids_str = subs_ids.join(',');
        }
        if (subs_ids_str) {
            setCookie(subScriptionPrefix + group_id, subs_ids_str);
        }
    });
    window.location.href = './classify.html?classify=subscription';
}
//////////////计算列表图片尺寸
function autoMySubscription(first) {
    var allWidth = $(".mySubscription").width();
    $(".mySubscription li").css("width", allWidth / 3.7);

    var liWidth = $(".mySubscription li").width() + 14; ////14的间距
    $(".mySubscription .content").each(function (index) {////计算每个ul的宽度
        var num = $(this).find("li").length;/////防止li换行加一个
        var ulWidth = liWidth * num + 10;
        $(this).children("ul").css("width", ulWidth);
    });

    var imgWidth = $(".mySubscription li").find("img").width();
    var imgHeight = Math.floor(180 * imgWidth / 120);
    $(".mySubscription li").find("img").attr("height", imgHeight);
    ////资讯短片
    var imgHeight2 = Math.floor(120 * imgWidth / 180);
    $(".mySubscription .shortInfo li").find("img").attr("height", imgHeight2);
    ////资讯短片更多
    var imgWidth = $(".searchList li").find("img").width();
    var imgHeight3 = Math.floor(120 * imgWidth / 180);
    $(".searchList .shortInfo li").find("img").attr("height", imgHeight3);
    if (first) {
        setCookie(WeChatHelperConstants.longImgHeightCookieKey, imgHeight);
        setCookie(WeChatHelperConstants.shortImgHeightCookieKey, imgHeight2);
        setCookie(WeChatHelperConstants.headerHeightCookieKey, $('.headerBar').height() + 1);
    }
};
function getSubScriptionSearchParams(params) {
    var type = parseInt(params.type, 10), code = params.code, contentType = params.contentType, pageIndex = params.pageIndex, pageSize = params.pageSize;
    var searchParams = {};
    switch (type) {
        case 0:
            searchParams.url = TYPE_FEED_URL;
            searchParams.param = {
                contentType: contentType,
                code: code,
                pageIndex: pageIndex,
                pageSize: pageSize
            };
            break;
        case 1:
            searchParams.url = AREA_FEED_URL;
            searchParams.param = {
                contentType: contentType,
                code: code,
                pageIndex: pageIndex,
                pageSize: pageSize
            };
            break;
        case 2:
            searchParams = null;
            break;
        case 3:
            searchParams.url = HOT_FEED_URL;
            searchParams.param = {
                contentType: contentType,
                code: code,
                pageIndex: pageIndex,
                pageSize: pageSize
            };
            break;
        case 4:
            searchParams.url = CONTAINER_FEED_URL;
            searchParams.param = {
                code: code,
                pageIndex: pageIndex,
                pageSize: pageSize
            };
            break;
        case 5:
            searchParams = null;
            break;
        case 6:
            searchParams = null;
            break;
    }
    ;
    return searchParams;
}
/**
 * param{code:'',pageSize:3,pageIndex:1}
 */
function getSubscriptionContent(content_id, param, first, from) {
    var searchParams = getSubScriptionSearchParams(param);
    var htmlStr = '';
    if (searchParams) {
        commonAjax(searchParams.url, searchParams.param, function (res) {
            $('#' + content_id + '_loading2').css('display', 'none');
            if (res && res.data && res.data.length > 0 && res.data[0].items && res.data[0].items.length > 0) {
                var items = res.data[0].items;
                htmlStr = assembleSearchResultHtml(items, searchParams.param.contentType, false, from);
                $('#' + content_id + '_more').css('display', 'block');
            } else {
                htmlStr = '<div class="subscriptionNoDatas"><div class="icon"></div><div class="text">暂无数据</div></div> ';
//                $('#' + content_id + '_more').css('display', 'none');
            }
            $('#' + content_id).html(htmlStr);
            $('#' + content_id + '_more').css('display', 'block');
            var imgArr = $('#' + content_id).find('.serimg');
            loadImg(imgArr, getDefaultImgSrc(WeChatHelperConstants.DefaultImgBgType.LargeProgram));
            autoMySubscription(first);
        });
    }

}
function subScriptionSearch(type, code, contentType, templateCode, pageIndex, count) {
    var htmlStr = '';
    var param = {type: type, code: code, contentType: contentType, pageIndex: pageIndex, pageSize: WeChatHelperConstants.SearchPageCapacity};
    var searchParams = getSubScriptionSearchParams(param);
    if (searchParams) {
        if (pageIndex > 1) {
            $('#loading').css('display', 'block');
        }
        WeChatHelperConstants.Loading = true;
        clearTimeout(WeChatHelperConstants.CommonAjaxTimer);
        var timeoutFlag = true;
        var timeout = false;
        WeChatHelperConstants.CommonAjaxTimer = setTimeout(function () {
            if (timeoutFlag) {
                timeout = true;
                if (!count) {
                    subScriptionSearch(type, code, contentType, templateCode, pageIndex, 1);
                } else {
                    $('#loading').css('display', 'none');
                    $('#loading2').css('display', 'none');
                    WeChatHelperConstants.Loading = false;
                }
            }
        }, WeChatHelperConstants.CommonAjaxTimeout);
        commonAjax(searchParams.url, searchParams.param,
            function (res) {
                if (WeChatHelperConstants.CommonAjaxTimeStamp == Number(this) && res) {
                    if (!timeout) {
                        timeoutFlag = false;
                        clearTimeout(WeChatHelperConstants.CommonAjaxTimer);
                        $('#loading').css('display', 'none');
                        $('#loading2').css('display', 'none');
                        if (res && res.data && res.data.length > 0 && res.data[0].items && res.data[0].items.length > 0) {
                            $('#total_page').val(res.data[0].count);
                            var items = res.data[0].items;
                            htmlStr = assembleSearchResultHtml(items, searchParams.param.contentType, false, WeChatHelperConstants.DetailPageFrom.SubScriptionMore);
                        } else {
                            htmlStr = '<div class="subscriptionNoDatas"><div class="icon"></div><div class="text">暂无数据</div></div> ';
                        }
                        $('#search_result').append(htmlStr);
                        if (contentType == WeChatHelperConstants.ContentType.SHORTVIDEO || contentType == WeChatHelperConstants.ContentType.SPORTS || contentType == WeChatHelperConstants.ContentType.MV || contentType == WeChatHelperConstants.ContentType.XIQU) {
                            $('#search_result').attr('class', 'shortInfo');
                        }
                        var imgArr = $('#search_result').find('.serimg');
                        loadImg(imgArr, getDefaultImgSrc(WeChatHelperConstants.DefaultImgBgType.LargeProgram));
                        WeChatHelperConstants.Loading = false;
                        autoMySubscription();
                    }
                }
            });
    }
};
function mySubScriptionScrollLoadData(scroll_top) {
    var _scrollTop = getScrollTop();
    if (typeof scroll_top != 'undefined' && null != scroll_top) {
        _scrollTop = scroll_top;
    }
    var _clientHeight = getClientHeight();
    //20：title高度，15：title的padding-bottom，14：ul的padding-bottom，1：ul的border-bottom，19/40：p文本的高度，8：p文本的margin-top，14：box的margin-top
    var longHeight = parseInt(getCookie(WeChatHelperConstants.longImgHeightCookieKey), 10) + 20 + 15 + 14 + 1 + 19 + 8 + 14;
    var shortHeight = parseInt(getCookie(WeChatHelperConstants.shortImgHeightCookieKey), 10) + 20 + 15 + 14 + 1 + 40 + 8 + 14;
    var upHeight = _scrollTop;
    var downHeight = _scrollTop + _clientHeight + $('.headerBar').height() + 1;
    var _height = 0;
    var loadIndex = [];
    lp:for (var i = 0; i < WeChatHelperConstants.SubScriptionObj.length; i++) {
        var contentType = WeChatHelperConstants.SubScriptionObj[i].contentType;
        var rowHeight = longHeight;
        if (contentType == WeChatHelperConstants.ContentType.SHORTVIDEO || contentType == WeChatHelperConstants.ContentType.SPORTS || contentType == WeChatHelperConstants.ContentType.MV || contentType == WeChatHelperConstants.ContentType.XIQU) {
            rowHeight = shortHeight;
        }
        _height += rowHeight;
        if (_height >= upHeight) {
            if (_height <= downHeight) {
                loadIndex.push(i);
                if (WeChatHelperConstants.SubScriptionObj[i + 1]) {
                    var _contentType = WeChatHelperConstants.SubScriptionObj[i + 1].contentType;
                    var _rowHeight = longHeight;
                    if (_contentType == WeChatHelperConstants.ContentType.SHORTVIDEO || _contentType == WeChatHelperConstants.ContentType.SPORTS || _contentType == WeChatHelperConstants.ContentType.MV || _contentType == WeChatHelperConstants.ContentType.XIQU) {
                        _rowHeight = shortHeight;
                    }
                    var _tempHeight = _height + _rowHeight;
                    if (_tempHeight > downHeight) {
                        if((i+1) <= WeChatHelperConstants.SubScriptionObj.length-1){
                            loadIndex.push(i+1);
                        }
                        break lp;
                    }
                } else {

                }
            } else {

            }
        }
    }
    if (loadIndex.length > 0) {
        for (var k = 0; k < loadIndex.length; k++) {
            var _obj = $('#subscription_list').find('.box').eq(loadIndex[k]).find('ul');
            if (!_obj.html()) {
                var content_id = WeChatHelperConstants.SubScriptionObj[loadIndex[k]].groupCode + subScriptionSeparate + WeChatHelperConstants.SubScriptionObj[loadIndex[k]].code;
                var param = {
                    type: WeChatHelperConstants.SubScriptionObj[loadIndex[k]].type,
                    code: WeChatHelperConstants.SubScriptionObj[loadIndex[k]].code,
                    contentType: WeChatHelperConstants.SubScriptionObj[loadIndex[k]].contentType,
                    pageSize: 10,
                    pageIndex: 1
                };
                getSubscriptionContent(content_id, param, false, WeChatHelperConstants.DetailPageFrom.MySubScription);
            }
        }
    }
    return loadIndex;
}
function albumList(code,contentType,count){
    var htmlStr = '';
    var param = {code:code};
    WeChatHelperConstants.Loading = true;
    clearTimeout(WeChatHelperConstants.CommonAjaxTimer);
    var timeoutFlag = true;
    var timeout = false;
    WeChatHelperConstants.CommonAjaxTimer = setTimeout(function () {
        if (timeoutFlag) {
            timeout = true;
            if (!count) {
                albumList(code,contentType,1);
            } else {
                $('#loading').css('display', 'none');
                $('#loading2').css('display', 'none');
                WeChatHelperConstants.Loading = false;
            }
        }
    }, WeChatHelperConstants.CommonAjaxTimeout);
    commonAjax(ALBUM_LIST_URL,param,
        function (res) {
            if (WeChatHelperConstants.CommonAjaxTimeStamp == Number(this) && res) {
                if (!timeout) {
                    timeoutFlag = false;
                    clearTimeout(WeChatHelperConstants.CommonAjaxTimer);
                    $('#loading').css('display', 'none');
                    $('#loading2').css('display', 'none');
                    try {
                        var data = res.subject;
                        var subjectPages = data.subjectPages[0];
                        var subjectRegions = subjectPages.subjectRegions, subjectReLen = subjectRegions.length;
                        $('#title_name').html(data.title);
                        for (var i = 0; i < subjectReLen; i++) {
                            if (subjectRegions[i].objectType == 6) {
                                var subjectItems = data.subjectItems[subjectRegions[i].objectCode];
                                htmlStr = assembleSearchResultHtml(subjectItems, null, false, WeChatHelperConstants.DetailPageFrom.AlbumList);

                            } else {
                                htmlStr = '<div class="subscriptionNoDatas"><div class="icon"></div><div class="text">暂无数据</div></div> ';
                            }
                        }
                    } catch (e) {
                        htmlStr = '<div class="subscriptionNoDatas"><div class="icon"></div><div class="text">暂无数据</div></div> ';
                    }
                    $('#search_result').append(htmlStr);
                    if (contentType == WeChatHelperConstants.ContentType.SHORTVIDEO || contentType == WeChatHelperConstants.ContentType.SPORTS || contentType == WeChatHelperConstants.ContentType.MV || contentType == WeChatHelperConstants.ContentType.XIQU) {
                        $('#search_result').attr('class', 'shortInfo');
                    }
                    var imgArr = $('#search_result').find('.serimg');
                    loadImg(imgArr, getDefaultImgSrc(WeChatHelperConstants.DefaultImgBgType.LargeProgram));
                    WeChatHelperConstants.Loading = false;
                    autoMySubscription();
                }
            }
        });
};

/**
 * version code update notes
 * 以下代码为修正后新版本代码，与百度云盘PC版机制保持一致
 */
/* 新的设备连接绑定校验机制，逻辑更为清晰，易扩展，通用化，更为人性化，更加安全 */


/**
 * 云端校验
 * @param param
 * @param successCallback 成功回调
 * @param failCallback 超时回调
 */
var connectAuthor = function(param,successCallback,failCallback,count){
    if(count){
        consoleLog('连接重试...')
    }
    if(param){
        consoleLog('云端校验开始 pin='+param.pin +' uid='+param.uid);
    }else{
        consoleLog('云端校验开始 无参数');
    }
    var para = null;
    param_if:if(param){
        if(param.pin){
            para = {pin:param.pin};
            break param_if;
        }
        if(param.uid){
            para = {userid:param.uid};
            break param_if;
        }
    }
    clearTimeout(globalTimer.connectAuthorTimer.timer);
    globalTimer.connectAuthorTimer = clone(globalTimerDefault.connectAuthorTimer);//置为默认值
    globalTimer.connectAuthorTimer.timer = setTimeout(function(){
        if(globalTimer.connectAuthorTimer.timeoutFlag){
            globalTimer.connectAuthorTimer.executeTimeoutFun = true;
            consoleLog('云端校验超时');
            //执行超时回调
            if(failCallback){
                consoleLog('云端校验超时执行超时回调方法');
                if(!count){
                    connectAuthor(param,successCallback,failCallback,1);
                }else{
                    failCallback();
                }
            }
        }
    },globalTimer.connectAuthorTimer.timeout);
    commonAjax(AUTHENTICATE_URL,para,function(res){
        if(!globalTimer.connectAuthorTimer.executeTimeoutFun){
            globalTimer.connectAuthorTimer.timeoutFlag = false;
            clearTimeout(globalTimer.connectAuthorTimer.timer);
            consoleLog('云端校验成功');
            if(res && typeof res.status != 'undefined'){
                var st = parseInt(res.status,10);
                if(st>0){
                    //执行成功回调
                    if(successCallback){
                        consoleLog('云端校验成功执行成功回调方法 status='+st);
                        successCallback(res);
                    }
                }else{
                    if(failCallback){
                        consoleLog('云端校验返回错误执行失败回调方法 status='+st);
                        failCallback();
                    }
                }

            }else{
                if(failCallback){
                    consoleLog('云端校验返回错误执行失败回调方法');
                    failCallback();
                }
            }
        }
    });
};
/**
 * 设备连接
 * @param device Device对象
 * @param successCallback 成功回调
 * @param failCallback 超时回调
 */
var connectDevice = function(device,successCallback,failCallback,newParam,count){
    if(count){
        consoleLog('连接重试...');
    }
    var url = 'http://'+device.deviceIp+':'+device.devicePort+'?callback=?';
    var param = {
        Action : Action.Event,
        eventType : EventType.Connect,
        clientId : device.deviceClientId,
        params: JSON.stringify({'connect':'connect'})
    };
    if(newParam){
        param = newParam;
    }
    consoleLog('连接设备开始 ip='+device.deviceIp+' port='+device.devicePort+' clientId='+device.deviceClientId);
    clearTimeout(globalTimer.connectDeviceTimer.timer);
    globalTimer.connectDeviceTimer = clone(globalTimerDefault.connectDeviceTimer);//置为默认值
    globalTimer.connectDeviceTimer.timer = setTimeout(function(){
        if(globalTimer.connectDeviceTimer.timeoutFlag){
            globalTimer.connectDeviceTimer.executeTimeoutFun = true;
            consoleLog('连接设备超时');
            //执行超时回调
            if(failCallback){
                consoleLog('连接设备超时执行超时回调方法');
                if(!count){
                    connectDevice(device,successCallback,failCallback,newParam,1);
                }else{
                    failCallback();
                }
            }
        }
    },globalTimer.connectDeviceTimer.timeout);
    commonAjax(url,param,function(res){
        if(!globalTimer.connectDeviceTimer.executeTimeoutFun){
            globalTimer.connectDeviceTimer.timeoutFlag = false;
            clearTimeout(globalTimer.connectDeviceTimer.timer);
            consoleLog('连接设备成功');
            //执行成功回调
            if(successCallback){
                consoleLog('连接设备成功执行成功回调方法');
                successCallback(res);
            }
            setWXUserInfoToApp(device);
        }
    });
};
/**
 * 播放视频
 * @param media Media对象
 * @param device Device对象
 * @param successCallback 成功回调
 * @param failCallback 超时回调
 */
var playVideo = function(media,device,successCallback,failCallback){
    var url = 'http://'+device.deviceIp+':'+device.devicePort+'?callback=?';
    var para = {
        action : ParamsAction.Play,
        url : media.url,
        title : media.title,
        path : media.path
    };
    var param = {
        Action : Action.Event,
        eventType : EventType.VideoPlay,
        params: JSON.stringify(para)
    };
    consoleLog('视频播放开始 ip='+device.deviceIp+' port='+device.devicePort+' clientId='+device.deviceClientId+' url='+media.url+' title='+media.title+' path='+media.path);
    clearTimeout(globalTimer.playVideoTimer.timer);
    globalTimer.playVideoTimer = clone(globalTimerDefault.playVideoTimer);//置为默认值
    globalTimer.playVideoTimer.timer = setTimeout(function(){
        if(globalTimer.playVideoTimer.timeoutFlag){
            globalTimer.playVideoTimer.executeTimeoutFun = true;
            consoleLog('视频播放超时');
            //执行超时回调
            if(failCallback){
                consoleLog('视频播放超时执行超时回调方法');
                failCallback();
            }
        }
    },globalTimer.playVideoTimer.timeout);
    commonAjax(url,param,function(res){
        if(!globalTimer.playVideoTimer.executeTimeoutFun){
            globalTimer.playVideoTimer.timeoutFlag = false;
            clearTimeout(globalTimer.playVideoTimer.timer);
            consoleLog('视频播放成功');
            //执行成功回调
            if(successCallback){
                consoleLog('视频播放成功执行成功回调方法');
                successCallback(res);
            }
        }
    });

};
/**
 * 获取本地连接设备历史记录
 * @returns {Array}
 */
function getOldDevices(){
    var uids = getCookie('MoreTVWeChatUIDS');
    var devices = [];
    if (uids) {
        var uidsArr = uids.split(',');
        for (var i = 0; i < uidsArr.length; i++) {
            if (i == 6) {
                break;
            }
            var info = getCookie('muid'+uidsArr[i]).split(',');
            if(info && info.length>0){
                var device = new Device();
                device.setDeviceId(uidsArr[i]);
                device.setDeviceIp(info[0].replace('http://',''));
                device.setDevicePort(info[1]);
                device.setDeviceName(info[2]);
                device.setDeviceClientId('wx-' + (+new Date()));
                devices.push(device);
            }
        }
    }
    return devices;
}
/**
 * 后台自动检测当前连接状态，自动连接设备;
 * @param callback Function 连接回调
 * callback参数1：param1，参数2：param2，参数3：param3
 * param1-! null,param2-! null:{有设备连接历史记录；a:param2存在deviceId，添加新设备，连接成功；b:param2无deviceId，连接不成功,显示第一个设备未连接状态}
 * param1-! null,param2-null:{有设备连接历史记录，连接成功；刷新设备列表}
 * param1-null,param2-! null:{无设备连接历史记录，但连接成功，刷新设备列表}
 * param1-null,param2-null:{无设备连接历史记录，未连接}
 * param3:设备连接返回信息，包含版本号等
 *
 */
var autoConnect = function (callback) {
    setCookie(ConnectDeviceFlagLocalKey, 'false');
    var devices = null;
    // 此处兼容较老版本，以免丢失用户设备连接历史记录数据
    var oldDevices = getOldDevices();
    if(!oldDevices || oldDevices.length<=0){
        var devicesJson = getCookie(DevicesLocalKey);
        if (devicesJson) {
            devices = JSON.parse(devicesJson || null);
        }
    }else{
        devices = oldDevices;
        setCookie('MoreTVWeChatUIDS','');
    }
    if (devices && devices.length > 0) {//云端获取有设备列表
        consoleLog('云端获取到该账号有连接设备记录，自动连接最后一次连接的设备');
        connectDevice(devices[0], function (res_1) {
            consoleLog('设备连接成功，进入百度云盘，设置标志位，刷新设备列表');
            //连接成功，进入百度云登录授权
            setCookie(ConnectDeviceFlagLocalKey, 'true');
            callback(devices, null ,res_1);//刷新设备列表
        }, function () {
            consoleLog('设备连接不成功，使用最后一次连接的设备uid从云端获取该设备最新信息');
            //连接不成功或超时，带上uid参数云端获取新的设备信息
            connectAuthor({uid: devices[0].deviceId}, function (res_2) {
                consoleLog('通过uid从云端获取设备信息成功');
                //云端获取新的设备信息成功，判断是否和当前设备信息一致
                var ip = res_2.info.ip;
                var port = res_2.info.port;
                var name = res_2.info.name;
                var userid = res_2.info.userid;
                var device = new Device();
                device.setDeviceId(userid);
                device.setDeviceIp(ip);
                device.setDevicePort(port);
                device.setDeviceName(name);
                device.setDeviceClientId('wx-' + (+new Date()));
                consoleLog('通过uid从云端获取设备最新信息如下：' + device);
                if ((ip + ':' + port) == (devices[0].deviceIp + ':' + devices[0].devicePort)) {
                    consoleLog('通过uid从云端获取设备ip和port与之前一致，无需再连接，无参数重新从云端获取当前网络下是否有可自动连接设备');
                    connectAuthor(null, function (res_4) {
                        consoleLog('无参数从云端获取到了当前网络下可自动连接的设备');
                        //云端无参数获取可连接设备信息成功，连接设备
                        var ip = res_4.info.ip;
                        var port = res_4.info.port;
                        var name = res_4.info.name;
                        var userid = res_4.info.userid;
                        var device = new Device();
                        device.setDeviceId(userid);
                        device.setDeviceIp(ip);
                        device.setDevicePort(port);
                        device.setDeviceName(name);
                        device.setDeviceClientId('wx-' + (+new Date()));
                        consoleLog('连接设备');
                        connectDevice(device, function (res_4) {
                            consoleLog('设备连接成功，进入百度云盘，设置标志位，刷新设备列表');
                            //连接成功，进入百度云登录授权
                            setCookie(ConnectDeviceFlagLocalKey, 'true');
                            callback(devices, device ,res_4);
                        }, function () {
                            consoleLog('无参数从云端获取到的设备连接不成功，输入设备码，设置标志位，刷新设备列表');
                            callback(devices,new Device());
                        });
                    }, function () {
                        consoleLog('无参数从云端获取无可自动连接设备，输入设备码，设置标志位，刷新设备列表');
                        callback(devices,new Device());
                    });
                } else {
                    consoleLog('通过uid从云端获取到的设备ip和port与之前不一致，重新连接设备');
                    connectDevice(device, function (res_5) {
                        consoleLog('通过uid从云端获取到的设备重新连接成功，进入百度云盘，设置标志位，刷新设备列表');
                        //连接成功，进入百度云登录授权
                        setCookie(ConnectDeviceFlagLocalKey, 'true');
                        devices[0] = device;
                        callback(devices, null ,res_5);//刷新设备列表
                    }, function () {
                        connectAuthor(null, function (res_8) {
                            consoleLog('无参数从云端获取到了当前网络下可自动连接的设备');
                            //云端无参数获取可连接设备信息成功，连接设备
                            var ip = res_8.info.ip;
                            var port = res_8.info.port;
                            var name = res_8.info.name;
                            var userid = res_8.info.userid;
                            var device = new Device();
                            device.setDeviceId(userid);
                            device.setDeviceIp(ip);
                            device.setDevicePort(port);
                            device.setDeviceName(name);
                            device.setDeviceClientId('wx-' + (+new Date()));
                            consoleLog('连接设备');
                            connectDevice(device, function (res_) {
                                consoleLog('设备连接成功，进入百度云盘，设置标志位，刷新设备列表');
                                //连接成功，进入百度云登录授权
                                setCookie(ConnectDeviceFlagLocalKey, 'true');
                                callback(devices, device ,res_);
                            }, function () {
                                consoleLog('无参数从云端获取到的设备连接不成功，输入设备码，设置标志位，刷新设备列表');
                                callback(devices,new Device());
                            });
                        }, function () {
                            consoleLog('无参数从云端获取无可自动连接设备，输入设备码，设置标志位，刷新设备列表');
                            callback(devices,new Device());
                        });
                    });
                }
            }, function () {
                consoleLog('通过uid从云端获取设备信息不成功，无参数从云端重新获取是否当前网络下是否有可自动连接的设备');
                //云端获取新的设备信息失败或超时，无参数请求云端看是否有可连接设备信息
                connectAuthor(null, function (res_3) {
                    consoleLog('通过uid从云端获取设备信息不成功，无参数从云端重新获取是否当前网络下有可自动连接的设备');
                    //云端无参数获取可连接设备信息成功，连接设备
                    var ip = res_3.info.ip;
                    var port = res_3.info.port;
                    var name = res_3.info.name;
                    var userid = res_3.info.userid;
                    var device = new Device();
                    device.setDeviceId(userid);
                    device.setDeviceIp(ip);
                    device.setDevicePort(port);
                    device.setDeviceName(name);
                    device.setDeviceClientId('wx-' + (+new Date()));
                    consoleLog('通过uid从云端获取设备信息不成功，无参数从云端重新获取可自动连接的设备信息');
                    consoleLog('连接设备');
                    connectDevice(device, function (res_4) {
                        consoleLog('通过uid从云端获取设备信息不成功，无参数从云端重新获取可自动连接的设备连接成功，进入百度云盘，设置标志位，刷新设备列表');
                        //连接成功，进入百度云登录授权
                        setCookie(ConnectDeviceFlagLocalKey, 'true');
                        callback(devices, device ,res_4);
                    }, function () {
                        consoleLog('通过uid从云端获取设备信息不成功，无参数从云端重新获取可自动连接的设备连接不成功，设置标志位，刷新设备列表');
                        callback(devices,new Device());
                    });
                }, function () {
                    consoleLog('通过uid从云端获取设备信息不成功，无参数从云端重新获取是否当前网络下有可自动连接的设备，设置标志位，刷新设备列表');
                    callback(devices,new Device());
                });
            });
        });
    } else {//云端获取没有设备列表
        consoleLog('云端获取到该账号没有连接设备记录，无参数从云端获取当前网络下是否有可自动连接的设备');
        connectAuthor(null, function (res_6) {
            consoleLog('云端获取到该账号没有连接设备记录，无参数从云端获取当前网络下有可自动连接的设备');
            //云端无参数获取可连接设备信息成功，连接设备
            var ip = res_6.info.ip;
            var port = res_6.info.port;
            var name = res_6.info.name;
            var userid = res_6.info.userid;
            var device = new Device();
            device.setDeviceId(userid);
            device.setDeviceIp(ip);
            device.setDevicePort(port);
            device.setDeviceName(name);
            device.setDeviceClientId('pc-' + (+new Date()));
            consoleLog('连接设备');
            connectDevice(device, function (res_7) {
                consoleLog('设备连接成功，进入百度云盘，设置标志位，刷新设备列表');
                //连接成功，进入百度云登录授权
                setCookie(ConnectDeviceFlagLocalKey, 'true');
                callback(null, device ,res_7);//刷新设备列表
            }, function () {
                consoleLog('设备连接不成功，输入设备码，设置标志位，刷新设备列表');
                callback(null,null);
            });
        }, function () {
            consoleLog('云端获取到该账号没有连接设备记录，无参数从云端获取当前网络下没有可自动连接的设备，输入设备码，设置标志位，刷新设备列表');
            callback(null,null);
        });
    }
};
/**
 * 通过设备码连接设备
 * @param pin_code
 * @param callback
 */
var pinCodeConnect = function(pin_code,callback){
    if (pin_code) {
        connectAuthor({pin: pin_code}, function (res) {
            consoleLog('通过设备码从云端获取到设备信息');
            //云端无参数获取可连接设备信息成功，连接设备
            var ip = res.info.ip;
            var port = res.info.port;
            var name = res.info.name;
            var userid = res.info.userid;
            var device = new Device();
            device.setDeviceId(userid);
            device.setDeviceIp(ip);
            device.setDevicePort(port);
            device.setDeviceName(name);
            device.setDeviceClientId('wx-' + (+new Date()));
            consoleLog('连接设备');
            connectDevice(device, function (res_2) {
                consoleLog('设备连接成功，，刷新设备列表');
                //连接成功，进入百度云登录授权
                setCookie(ConnectDeviceFlagLocalKey, 'true');
                callback(device ,res_2);
            }, function () {
                consoleLog('设备连接不成功，输入设备码，设置标志位，刷新设备列表');
                callback(null);
            });
        }, function () {
            consoleLog('云端获取设备信息失败，输入设备码，设置标志位，刷新设备列表');
            callback(null);
        });
    } else {
        consoleLog('设备码参数为空');
        callback(null);
    }
};
/**
 * 刷新设备列表
 * @param devices
 * @param newDevice
 */
function refreshDevices(devices,newDevice){
    var deviceHtmlStr = '';
    var tempDevices = [];
    if(devices){
        if(newDevice){
            if(newDevice.deviceId){
                var idx = existDeviceIndex(devices,newDevice);
                if(idx != -1){
                    devices.splice(idx,1);
                }
                devices.unshift(newDevice);
                setCookie(CurrentDeviceLocalKey, JSON.stringify(newDevice));
            }else{
                setCookie(CurrentDeviceLocalKey,'');
            }
            for (var i = 0; i < devices.length; i++) {
                if (i == 5) {
                    break;
                }
                if (i == 0) {
                    if(newDevice.deviceId){
                        $('#selectTv').html('<span>' + devices[0].deviceName + '</span><i></i>');
                    }else{
                        $('#selectTv').html('<span>' + devices[0].deviceName + '</span>[<span class="unconnect">×</span>]<i></i>');
                    }
                } else {
                    deviceHtmlStr += '<li onclick="changeDevice(\'' + devices[i].deviceId + '\');" id="' + devices[i].deviceId + '" class="tv"><i class="tv">&nbsp;</i><span>' + devices[i].deviceName + '</span></li>';
                }
                tempDevices.push(devices[i]);
            }
            deviceHtmlStr += '<li onclick="javascript:popInputPin();" id="addBoxes"><i class="add">&nbsp;</i><span>添加新设备</span></li>';
            $('#mydevices').html(deviceHtmlStr);
            setCookie(DevicesLocalKey, JSON.stringify(tempDevices));
        }else{
            for(var i=0; i<devices.length; i++){
                if(i == 5){
                    break;
                }
                if(i == 0){
                    $('#selectTv').html('<span>'+devices[0].deviceName+'</span><i></i>');
                }else{
                    deviceHtmlStr += '<li onclick="changeDevice(\''+devices[i].deviceId+'\');" id="' + devices[i].deviceId + '" class="tv"><i class="tv">&nbsp;</i><span>' + devices[i].deviceName + '</span></li>';
                }
                tempDevices.push(devices[i]);
            }
            deviceHtmlStr += '<li onclick="javascript:popInputPin();" id="addBoxes"><i class="add">&nbsp;</i><span>添加新设备</span></li>';
            $('#mydevices').html(deviceHtmlStr);
            setCookie(DevicesLocalKey,JSON.stringify(tempDevices));
            setCookie(CurrentDeviceLocalKey,JSON.stringify(tempDevices[0]));
        }
    }else{
        if(newDevice){
            $('#selectTv').html('<span>'+newDevice.deviceName+'</span><i></i>');
            deviceHtmlStr += '<li onclick="javascript:popInputPin();" id="addBoxes"><i class="add">&nbsp;</i><span>添加新设备</span></li>';
            $('#mydevices').html(deviceHtmlStr);
            setCookie(DevicesLocalKey,JSON.stringify([newDevice]));
            setCookie(CurrentDeviceLocalKey,JSON.stringify(newDevice));
        }else{
            $('#selectTv').html('<span>未连接设备</span><i></i>');
            deviceHtmlStr += '<li onclick="javascript:popInputPin();" id="addBoxes"><i class="add">&nbsp;</i><span>添加新设备</span></li>';
            $('#mydevices').html(deviceHtmlStr);
            setCookie(DevicesLocalKey,'');
            setCookie(CurrentDeviceLocalKey,'');
        }
    }
};
/**
 * 刷新设备simkey
 * @param devices
 * @param newDevice
 */
function refreshSimKeyDevices(deviceSimkeys, newDeviceSimkey){
    var deviceHtmlStr = '';
    var tempDeviceSimkeys = [];
    if(deviceSimkeys){
        if(newDeviceSimkey){
            if(newDeviceSimkey.deviceId){
                var idx = existDeviceSimKeyIndex(deviceSimkeys,newDeviceSimkey);
                if(idx > -1){
                    deviceSimkeys.splice(idx,1);
                }
               deviceSimkeys.unshift(newDeviceSimkey);
               console.log(deviceSimkeys);
               setSimKeyCookie(CurrentDevicesSimKeyUrl, JSON.stringify(newDeviceSimkey));
            }else{
                setSimKeyCookie(CurrentDevicesSimKeyUrl,'');
            }
            for (var i = 0; i < deviceSimkeys.length; i++) {
                if (i == 5) {
                    break;
                }
                if (i == 0) {
                    if(newDeviceSimkey.deviceId){
                        $('#selectTv').html('<span>' + deviceSimkeys[0].deviceAddr + '</span><i></i>');
                    }else{
                        $('#selectTv').html('<span>' + deviceSimkeys[0].deviceAddr + '</span>[<span class="unconnect">×</span>]<i></i>');
                    }
                } else {
                    deviceHtmlStr += '<li onclick="changeDeviceSimKey(\'' + deviceSimkeys[i].deviceId + '\');" id="' + deviceSimkeys[i].deviceId + '" class="tv"><i class="tv">&nbsp;</i><span>' + deviceSimkeys[i].deviceAddr + '</span></li>';
                }
                tempDeviceSimkeys.push(deviceSimkeys[i]);
            }
            deviceHtmlStr += '<li onclick="javascript:popInputPin();" id="addBoxes"><i class="add">&nbsp;</i><span>添加新设备</span></li>';
            $('#mydevices').html(deviceHtmlStr);
            console.log("*****1" + JSON.stringify(tempDeviceSimkeys));
            setSimKeyCookie(DevicesSimKeyUrl, JSON.stringify(tempDeviceSimkeys));
            console.log("*****2" + getSimKeyCookie(DevicesSimKeyUrl));

        }else{
            for(var i=0; i<deviceSimkeys.length; i++){
                if(i == 5){
                    break;
                }
                if(i == 0){
                    $('#selectTv').html('<span>'+deviceSimkeys[0].deviceAddr+'</span><i></i>');
                }else{
                    deviceHtmlStr += '<li onclick="changeDeviceSimKey(\''+deviceSimkeys[i].deviceId+'\');" id="' + deviceSimkeys[i].deviceId + '" class="tv"><i class="tv">&nbsp;</i><span>' + deviceSimkeys[i].deviceAddr + '</span></li>';
                }
                tempDeviceSimkeys.push(deviceSimkeys[i]);
            }
            deviceHtmlStr += '<li onclick="javascript:popInputPin();" id="addBoxes"><i class="add">&nbsp;</i><span>添加新设备</span></li>';
            $('#mydevices').html(deviceHtmlStr);
            setSimKeyCookie(DevicesSimKeyUrl,JSON.stringify(tempDeviceSimkeys));
            setSimKeyCookie(CurrentDevicesSimKeyUrl,JSON.stringify(tempDeviceSimkeys[0]));
        }
    }else{
        if(newDeviceSimkey){
            $('#selectTv').html('<span>'+newDeviceSimkey.deviceAddr+'</span><i></i>');
            deviceHtmlStr += '<li onclick="javascript:popInputPin();" id="addBoxes"><i class="add">&nbsp;</i><span>添加新设备</span></li>';
            $('#mydevices').html(deviceHtmlStr);
            setSimKeyCookie(DevicesSimKeyUrl,JSON.stringify([newDeviceSimkey]));
            setSimKeyCookie(CurrentDevicesSimKeyUrl,JSON.stringify(newDeviceSimkey));
        }else{
            $('#selectTv').html('<span>未连接设备</span><i></i>');
            deviceHtmlStr += '<li onclick="javascript:popInputPin();" id="addBoxes"><i class="add">&nbsp;</i><span>添加新设备</span></li>';
            $('#mydevices').html(deviceHtmlStr);
            setSimKeyCookie(DevicesSimKeyUrl,'');
            setSimKeyCookie(CurrentDevicesSimKeyUrl,'');
        }
    }
};

var existDeviceIndex = function(devices,device){
    if (!devices || devices.length <= 0 || !device){
        return -1;
    }
    for (var k = 0; k < devices.length; k++) {
        if(device.deviceId == devices[k].deviceId ){
            return k;
        }
    }
    return -1;
};
var existDeviceSimKeyIndex = function(devices,device){
    if (!devices || devices.length <= 0 || !device){
        return -1;
    }

    for (var k = 0; k < devices.length; k++) {
        if(device.deviceId == devices[k].deviceId ){
            return k;
        }
    }
    return -2;
};
/**
 * 切换设备
 * @param deviceId
 */
function changeDevice(deviceId) {
    var temp = null;
    var localDevices = JSON.parse(getCookie(DevicesLocalKey) || null);
    var index = -1;
    if (deviceId && localDevices && localDevices.length > 0) {
        for(var i=0; i<localDevices.length; i++){
            if(localDevices[i].deviceId == deviceId){
                temp = localDevices[i];
                index = i;
                break;
            }
        }
    }
    if(temp){
        connectDevice(temp,function(res){
            localDevices.splice(index,1);
            localDevices.unshift(temp);
            refreshDevices(localDevices,null);
            play(null,temp);
            setCookie(ConnectDeviceFlagLocalKey, 'true');
            toastShow('设备切换成功');
            return;
        },function(){
            consoleLog('设备切换失败，从云端获取最新设备信息');
            connectAuthor({uid:deviceId}, function (res_3) {
                consoleLog('通过uid从云端获取设备信息成功');
                var ip = res_3.info.ip;
                var port = res_3.info.port;
                var name = res_3.info.name;
                var userid = res_3.info.userid;
                var device = new Device();
                device.setDeviceId(userid);
                device.setDeviceIp(ip);
                device.setDevicePort(port);
                device.setDeviceName(name);
                device.setDeviceClientId('wx-' + (+new Date()));
                if(ip == temp.deviceId && port == temp.devicePort){
                    toastShow('无法连接，设备切换失败');
                    return;
                }
                consoleLog('连接设备');
                connectDevice(device, function (res_4) {
                    consoleLog('设备连接成功');
                    localDevices.splice(index,1);
                    localDevices.unshift(device);
                    refreshDevices(localDevices,null);
                    play(null,device);
                    setCookie(ConnectDeviceFlagLocalKey, 'true');
                    toastShow('设备切换成功');
                    return;
                }, function () {
                    consoleLog('设备连接失败');
                    toastShow('无法连接，设备切换失败');
                    return;
                });
            }, function () {
                consoleLog('设备连接失败');
                toastShow('无法连接，设备切换失败');
                return;
            });
        });
    }else{
        consoleLog('设备不存在');
        toastShow('设备不存在，设备切换失败');
        return;
    }
};
/**
 * 切换设备
 * @param deviceId
 */
function changeDeviceSimKey(deviceId) {
    setCookie(CurrentDevicesSimKeyUrl, deviceId);
    return;
};
/**
 * 输入设备码执行方法
 */
function pinEnter() {
    var pinCode = $('#pin_code').val();
    if (pinCode != '') {
        cancelInputPin();
        loadingShow();
        pinCodeConnect(pinCode, function (device) {
            if (WeChatHelperConstants.CurrentEventType == WeChatHelperConstants.EventType.Play) {
                if (device) {
                    cancelLoadingShow();
                    if(currentWXUser){
                        danMuPlay(null,device);
                    }else{
                        play(null,device);
                    }
                    var devices = JSON.parse(getCookie(DevicesLocalKey) || null);
                    refreshDevices(devices,device);
                } else {
                    popInputPin();
                    toastShow('连接错误，请重试');
                }
            }
            if (WeChatHelperConstants.CurrentEventType == WeChatHelperConstants.EventType.AddDevice){
                if(device){
                    cancelLoadingShow();
                    var devices = JSON.parse(getCookie(DevicesLocalKey) || null);
                    refreshDevices(devices,device);
                }else{
                    popInputPin();
                    toastShow('连接错误，请重试');
                }
            }

        });
    } else {
        toastShow('请输入设备码');
    }
};
/**
 * 输入设备simkey url
 */
function simKeyUrlpinEnter() {
    var pinCode = $('#pin_code').val();
    if (pinCode != '') {
        if(pinCode.charAt(0) != '{' ){
            cancelInputPin();
            var deviceurl = {"deviceId": pinCode, "deviceAddr":pinCode};
            ConnectsimKeyDevice(deviceurl);
        }else{
            cancelInputPin();
            QRImageConnectDevice(pinCode);
        }
    } else {
        toastShow('请输入设备服务地址');
    }
};
/**
 * 二维码连接
 */
function QRImageConnectDevice(pinCode) {
    var qrdevice = JSON.parse(pinCode);
    if(qrdevice == null || qrdevice.mDeviceAddrList == null){
        toastShow('请输入设备服务地址错误');
        return;
    }
    var isSuccess = false;
    var simkeydevice;
    for(var i=0; i<qrdevice.mDeviceAddrList.length; i++){
        var deviceadd = qrdevice.mDeviceAddrList[i];
        var url = "http://" + deviceadd + "/ConnectDevice";
        var _data = { "mDeviceID":qrdevice.mDeviceID};
        $.ajax({url:url,
            type:'POST',
            timeout:10000, //超时时间设置，单位毫秒
            data:JSON.stringify(_data),
            dataType:'json',
            async:false,
            success: function (data) {
                console.log(data);
                simkeydevice = {"deviceId": qrdevice.mDeviceID, "deviceAddr":deviceadd};
                isSuccess = true;
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log(errorThrown);
                isSuccess = false;
            }
        });

        if(isSuccess == true){
            break;
        }
    }
    if(isSuccess == true){
        var deviceSimKeys = JSON.parse(getSimKeyCookie(DevicesSimKeyUrl) || null);
        console.log("==========="+getSimKeyCookie(DevicesSimKeyUrl));
        refreshSimKeyDevices(deviceSimKeys, simkeydevice);
    }else{
        toastShow('请输入设备服务地址错误');
    }
};
/**
 * 输入设备simkey url
 */
function ConnectsimKeyDevice(simkeydevice) {
    if(simkeydevice == null || simkeydevice.deviceAddr == ""){
        return;
    }
    var url = "http://" + simkeydevice.deviceAddr + "/ConnectDevice";
    var _data = { "mDeviceID":simkeydevice.deviceId};
    $.ajax({url:url,
        type:'POST',
        timeout:10000, //超时时间设置，单位毫秒
        data:JSON.stringify(_data),
        dataType:'json',
        async:false,
        success: function (data) {
            console.log(data);
            var deviceSimKeys = JSON.parse(getSimKeyCookie(DevicesSimKeyUrl) || null);
            console.log("==========="+getSimKeyCookie(DevicesSimKeyUrl));
            refreshSimKeyDevices(deviceSimKeys, simkeydevice);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log(errorThrown);
            toastShow('连接设备失败');
        }
    });
};
/**
 * 推送播放执行方法
 * @param params
 * @param device
 */
function play(params,device) {
    WeChatHelperConstants.CurrentEventType = WeChatHelperConstants.EventType.Play;
    var currentDevice;
    if(device){
        currentDevice = device;
    }else{
        currentDevice = JSON.parse(getCookie(CurrentDeviceLocalKey) || null);
    }
    if (currentDevice) {
        var pSid,sSid,contentType,playType;
        if(params){
            pSid = params.pSid;
            sSid = params.sSid;
            contentType = params.contentType;
            playType = params.playType;
        }
        if (WeChatHelperConstants.DetailpSid && WeChatHelperConstants.DetailsSid && WeChatHelperConstants.DetailContentType) {
            pSid = WeChatHelperConstants.DetailpSid;
            sSid = WeChatHelperConstants.DetailsSid;
            contentType = WeChatHelperConstants.DetailContentType;
            playType = WeChatHelperConstants.DetailPlayType;
        }
        var Paras = {
            Action: WeChatHelperConstants.Action.Play,
            pSid: pSid,
            sSid: sSid,
            contentType: contentType
        };
        var url = 'http://' + currentDevice.deviceIp + ':' + currentDevice.devicePort + '?callback=?';
        consoleLog('推送播放开始 url=' + url);
        clearTimeout(globalTimer.playVideoTimer.timer);
        globalTimer.playVideoTimer = clone(globalTimerDefault.playVideoTimer);//置为默认值
        globalTimer.playVideoTimer.timer = setTimeout(function () {
            if (globalTimer.playVideoTimer.timeoutFlag) {
                globalTimer.playVideoTimer.executeTimeoutFun = true;
                consoleLog('连接设备超时');
                //执行超时回调
                popAlert();
            }
        }, globalTimer.playVideoTimer.timeout);
        commonAjax(url, Paras, function (res) {
            if (!globalTimer.playVideoTimer.executeTimeoutFun) {
                globalTimer.playVideoTimer.timeoutFlag = false;
                clearTimeout(globalTimer.playVideoTimer.timer);
                consoleLog('连接设备成功');
                //执行成功回调
                window.location.href = './play.html?' + 'pSid=' + escape(pSid) + '&sSid=' + escape(sSid) + '&contentType=' + escape(contentType) + '&playType=' + escape(playType);
            }
        });
    } else {
        popInputPin();
    }
};
/**
 * 播控
 * @param params
 */
function playControl(params){
    var device = JSON.parse(getCookie(CurrentDeviceLocalKey) || null);
    if(device){
        var url = 'http://' + device.deviceIp + ':' + device.devicePort + '?callback=?';
        consoleLog('播控开始 url=' + url);
        clearTimeout(globalTimer.playControlTimer.timer);
        globalTimer.playControlTimer = clone(globalTimerDefault.playControlTimer);//置为默认值
        globalTimer.playControlTimer.timer = setTimeout(function () {
            if (globalTimer.playControlTimer.timeoutFlag) {
                globalTimer.playControlTimer.executeTimeoutFun = true;
                consoleLog('连接设备超时');
                //执行超时回调
                popAlert();
                toastShow('连接失败，请重试!');
            }
        }, globalTimer.playControlTimer.timeout);
        commonAjax(url, params, function (res) {
            if (!globalTimer.playControlTimer.executeTimeoutFun) {
                globalTimer.playControlTimer.timeoutFlag = false;
                clearTimeout(globalTimer.playControlTimer.timer);
                consoleLog('连接设备成功');
                //执行成功回调
            }
        });
    }
};

function getAccessTokenSend(mwuid,success,fail){
    clearTimeout(globalTimer.getAccessTokenTimer.timer);
    globalTimer.getAccessTokenTimer = clone(globalTimerDefault.getAccessTokenTimer);//置为默认值
    globalTimer.getAccessTokenTimer.timer = setTimeout(function(){
        if(globalTimer.getAccessTokenTimer.timeoutFlag){
            globalTimer.getAccessTokenTimer.executeTimeoutFun = true;
            consoleLog('获取AccessToken超时');
            //执行超时回调
            if(fail){
                consoleLog('获取AccessToken超时执行超时回调方法');
                fail(null);
            }
        }
    },globalTimer.getAccessTokenTimer.timeout);
    commonAjax(GET_ACCESS_TOKEN_URL,{mwid:mwuid},function(res){
        if(!globalTimer.getAccessTokenTimer.executeTimeoutFun){
            globalTimer.getAccessTokenTimer.timeoutFlag = false;
            clearTimeout(globalTimer.getAccessTokenTimer.timer);
            consoleLog('获取AccessToken成功');
            if(res && typeof res.status != 'undefined'){
                var st = parseInt(res.status,10);
                if(st>0){
                    //执行成功回调
                    if(success){
                        consoleLog('获取AccessToken成功执行成功回调方法 status='+st);
                        success(res);
                    }
                }else{
                    if(fail){
                        consoleLog('获取AccessToken返回错误执行失败回调方法 status='+st);
                        fail(null);
                    }
                }

            }else{
                if(fail){
                    consoleLog('获取AccessToken结果为null执行失败回调方法');
                    fail(null);
                }
            }
        }
    });
};
function getWXUserInfo(mwuid,access_token){
    commonAjax(GET_WX_USER_INFO_URL+mwuid+'?accesstoken='+access_token+'&callback=?',null,function(res){
        if(res){
            if(res.status+'' == '-1'){
                getAccessTokenSend(mwuid,function(res){
                    request_access_token = res.accesstoken;
                    var new_accessinfo = {
                        access_token : res.accesstoken,
                        expire : res.expire,
                        gettime : (+new Date())
                    };
                    setCookie(accessInfoLocalKey,JSON.stringify(new_accessinfo));
                    getWXUserInfo(mwuid,request_access_token);
                });
            }else{
                res = res.userinfo;
                var wxUser = new WXUser();
                wxUser.mwuid = mwuid;
                wxUser.openid = res.openid;
                wxUser.nickname = res.nickname;
                wxUser.sex = res.sex;
                wxUser.language = res.language;
                wxUser.city = res.city;
                wxUser.province = res.province;
                wxUser.country = res.country;
                wxUser.headimgurl = res.headimgurl;
                wxUser.privilege = res.privilege;
                if (currentWXUser) {
                    wxUser.sid = currentWXUser.sid;
                    wxUser.pin = currentWXUser.pin;
                    wxUser.title = currentWXUser.title;
                    wxUser.contentType = currentWXUser.contentType;
                    wxUser.linkType = currentWXUser.linkType;
                    wxUser.device = currentWXUser.device;
                    wxUser.mac = currentWXUser.mac;
                    wxUser.uid = currentWXUser.uid;
                    wxUser.feedType = currentWXUser.feedType;
                }
                currentWXUser = wxUser;
                setCookie(WXUserInfoLocalKey, JSON.stringify(wxUser));
                var device = JSON.parse(getCookie(CurrentDeviceLocalKey) || null);
                setWXUserInfoToApp(device);
            }
        }
    });
};
function setWXUserInfoToApp(device){
    return;
    var wxUserInfo = JSON.parse(getCookie(WXUserInfoLocalKey) || null);
    if (!wxUserInfo || !device) {
        return;
    }
    var url = 'http://' + device.deviceIp + ':' + device.devicePort + '?callback=?';
    var _keyValue = {
        mwid: wxUserInfo.mwuid,
        openid: wxUserInfo.openid,
        nickname: wxUserInfo.nickname,
        sex: wxUserInfo.sex,
        language: wxUserInfo.language,
        city: wxUserInfo.city,
        province: wxUserInfo.province,
        country: wxUserInfo.country,
        headimgurl: wxUserInfo.headimgurl,
        privilege: wxUserInfo.privilege
    };
    var param = {
        Action: Action.Event,
        eventType: EventType.WeiXinControl,
        params: JSON.stringify({'userInfo': _keyValue})
    };
    clearTimeout(globalTimer.setWXUserInfoToAppTimer.timer);
    globalTimer.setWXUserInfoToAppTimer = clone(globalTimerDefault.setWXUserInfoToAppTimer);//置为默认值
    globalTimer.setWXUserInfoToAppTimer.timer = setTimeout(function () {
        if (globalTimer.setWXUserInfoToAppTimer.timeoutFlag) {
            globalTimer.setWXUserInfoToAppTimer.executeTimeoutFun = true;
            consoleLog('连接设备超时');
        }
    }, globalTimer.setWXUserInfoToAppTimer.timeout);
    commonAjax(url, param, function (res) {
        if (!globalTimer.setWXUserInfoToAppTimer.executeTimeoutFun) {
            globalTimer.setWXUserInfoToAppTimer.timeoutFlag = false;
            clearTimeout(globalTimer.setWXUserInfoToAppTimer.timer);
            consoleLog('连接设备成功');
            consoleLog('微信信息发送成功');
            //执行成功回调
        }
    });
};
function getAccessToken(mwuid){
    /* 判断access_token是否过期，过期则重新从服务器获取最新的access_token */
    var access = getCookie(accessInfoLocalKey);
    var accessinfo = null;
    if(access){
        accessinfo = JSON.parse(access || null);
    }
    if(accessinfo){
        var expire = parseInt(accessinfo.expire,10)*1000;
        var gettime = parseInt(accessinfo.gettime,10);
        if((expire+gettime)<=(+new Date())){
            getAccessTokenSend(mwuid,function(res){
                request_access_token = res.accesstoken;
                var new_accessinfo = {
                    access_token : res.accesstoken,
                    expire : res.expire,
                    gettime : (+new Date())
                };
                setCookie(accessInfoLocalKey,JSON.stringify(new_accessinfo));
                getWXUserInfo(mwuid,request_access_token);
            },function(){
                setCookie(accessInfoLocalKey,'');
            });
        }else{
            request_access_token = accessinfo.access_token;
            getWXUserInfo(mwuid,request_access_token);
        }
    }else{
        getAccessTokenSend(mwuid,function(res){
            request_access_token = res.accesstoken;
            var new_accessinfo = {
                access_token : res.accesstoken,
                expire : res.expire,
                gettime : (+new Date())
            };
            setCookie(accessInfoLocalKey,JSON.stringify(new_accessinfo));
            getWXUserInfo(mwuid,request_access_token);
        },function(){
            setCookie(accessInfoLocalKey,'');
        });
    }
    /* access_token判断结束 */
};
/**
 * 用户实例对象
 * @constructor
 */
var User = function(){
    this.uid = '';
    this.uname = '';
    this.portrait = '';
    this.loginTime = 0;
    this.accessToken = '';
    this.expiresIn = 0;
    this.devices = [];
    this.firstFlag = true;

    this.setUid = function(uid){
        this.uid = uid;
    };
    this.getUid = function(){
        return this.uid;
    };
    this.setUname = function(uname){
        this.uname = uname;
    };
    this.getUname = function(){
        return this.uname;
    };
    this.setPortrait = function(portrait){
        this.portrait = portrait;
    };
    this.getPortrait = function(){
        return this.portrait;
    };
    this.setLoginTime = function(loginTime){
        this.loginTime = loginTime;
    };
    this.getLoginTime = function(){
        return this.loginTime;
    };
    this.setAccessToken = function(accessToken){
        this.accessToken = accessToken;
    };
    this.getAccessToken = function(){
        return this.accessToken;
    };
    this.setExpiresIn = function(expiresIn){
        this.expiresIn = expiresIn;
    };
    this.getExpiresIn = function(){
        return this.expiresIn;
    };
    this.setDevices = function(devices){
        this.devices = devices;
    };
    this.getDevices = function(){
        return this.devices;
    };
    this.setFirstFlag = function(firstFlag){
        this.firstFlag = firstFlag;
    };
    this.getFirstFlag = function(){
        return this.firstFlag;
    };
};
/**
 * 设备simkeyurl
 * @constructor
 */
var DeviceSimKey = function(){
    this.deviceId = '';
    this.deviceAddr = '';

    this.setDeviceId = function(deviceId){
        this.deviceId = deviceId;
    };
    this.getDeviceId = function(){
        return this.deviceId;
    };
    this.setDeviceAddr = function(deviceAddr){
        this.deviceAddr = deviceAddr;
    };
    this.getDeviceAddr = function(){
        return this.deviceAddr;
    };
};
/**
 * key req
 * @constructor
 */
var SimKeyRequst = function(){
    this.mDeviceID = '';
    this.mKeyID = 1;

    this.setmDeviceID = function(mDeviceID){
        this.mDeviceID = mDeviceID;
    };
    this.getmDeviceID = function(){
        return this.mDeviceID;
    };
    this.setmKeyID = function(mKeyID){
        this.mKeyID = mKeyID;
    };
    this.getmKeyID = function(){
        return this.mKeyID;
    };
};
/**
 * key rsp
 * @constructor
 */
var SimKeyRsp = function(){
    this.mErrorCode = 0;
    this.mErrorDes = "";

    this.setmErrorCode = function(mErrorCode){
        this.mErrorCode = mErrorCode;
    };
    this.getmErrorCode = function(){
        return this.mErrorCode;
    };
    this.setmErrorDes = function(mErrorDes){
        this.mErrorDes = mErrorDes;
    };
    this.getmErrorDes = function(){
        return this.mErrorDes;
    };
};
/**
 * key rsp
 * @constructor
 */
var QRImageDeviceInfo = function(){
    this.mDeviceID = 0;
    this.mDeviceAddrList = "";

    this.setmDeviceID = function(mDeviceID){
        this.mDeviceID = mDeviceID;
    };
    this.getmDeviceID = function(){
        return this.mDeviceID;
    };
    this.mDeviceAddrList = function(mDeviceAddrList){
        for(var i = 0; i < mDeviceAddrList.length; i++){
            this.mDeviceAddrList.push(mDeviceAddrList[i]);
        }
    };
    this.getmErrorDes = function(){
        return this.mDeviceAddrList;
    };
};
/**
 * 设备实例对象
 * @constructor
 */
var Device = function(){
    this.deviceId = '';
    this.deviceName = '';
    this.deviceIp = '';
    this.devicePort = '';
    this.deviceOrder = 0;
    this.deviceConnectTime = 0;
    this.deviceClientId = '';

    this.setDeviceId = function(deviceId){
        this.deviceId = deviceId;
    };
    this.getDeviceId = function(){
        return this.deviceId;
    };
    this.setDeviceName = function(deviceName){
        this.deviceName = deviceName;
    };
    this.getDeviceName = function(){
        return this.deviceName;
    };
    this.setDeviceIp = function(deviceIp){
        this.deviceIp = deviceIp;
    };
    this.getDeviceIp = function(){
        return this.deviceIp;
    };
    this.setDevicePort = function(devicePort){
        this.devicePort = devicePort;
    };
    this.getDevicePort = function(){
        return this.devicePort;
    };
    this.setDeviceOrder = function(deviceOrder){
        this.deviceOrder = deviceOrder;
    };
    this.getDeviceOrder = function(){
        return this.deviceOrder;
    };
    this.setDeviceConnectTime = function(deviceConnectTime){
        this.deviceConnectTime = deviceConnectTime;
    };
    this.getDeviceConnectTime = function(){
        return this.deviceConnectTime;
    };
    this.setDeviceClientId = function(deviceClientId){
        this.deviceClientId = deviceClientId;
    };
    this.getDeviceClientId = function(){
        return this.deviceClientId;
    };
};
/**
 * 多媒体实例对象
 * @constructor
 */
var Media = function(){
    this.url = '';
    this.title = '';
    this.path = '';
    this.type = '';
    this.bdAccount = '';

    this.setUrl = function(url){
        this.url = url;
    };
    this.getUrl = function(){
        return this.url;
    };
    this.setTitle = function(title){
        this.title = title;
    };
    this.getTitle = function(){
        return this.title;
    };
    this.setPath = function(path){
        this.path = path;
    };
    this.getPath = function(){
        return this.path;
    };
    this.setType = function(type){
        this.type = type;
    };
    this.getType = function(){
        return this.type;
    };
    this.setBdAccount = function(bdAccount){
        this.bdAccount = bdAccount;
    };
    this.getBdAccount = function(){
        return this.bdAccount;
    };



};
var WXUser = function () {
    this.mwuid = '',
    this.openid = '',
        this.nickname = '',
        this.sex = '',
        this.language = '',
        this.city = '',
        this.province = '',
        this.country = '',
        this.headimgurl = '',
        this.privilege = [],
        this.sid='',
        this.access_token='',
        this.title='',
        this.pin='',
        this.contentType='',
        this.linkType=''


};
/*==============视频分类==============*/